Hibernate – One-to-One example (XML Mapping)

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity.

In this tutorial, we show you how to work with one-to-one table relationship in Hibernate, via XML mapping file (hbm).

Tools and technologies used in this tutorials :

  1. Hibernate 3.6.3.Final
  2. MySQL 5.1.15
  3. Maven 3.0.3
  4. Eclipse 3.6

Project Structure

See the final project structure of this tutorial.

one to one project structure

Project Dependency

Get hibernate.jar from JBoss repository, Maven will take care all the related dependencies for you.

File : pom.xml


<project ...>

	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
		</repository>
	</repositories>

	<dependencies>

		<!-- MySQL database driver -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.3.Final</version>
		</dependency>

		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
		</dependency>

	</dependencies>
</project>

1. “One-to-one” table relationship

A one-to-one relationship table design, a STOCK table contains exactly one record in STOCK_DETAIL table. Both tables have the same Stock_Id as primary key. In STOCK_DETAIL table, Stock_Id is the primary key and also a foreign key to STOCK table. This is the common way of define “one-to-one” table relationship.

one to one relationship

To get the STOCK and STOCK_DETAIL table script, refer to this “one to one table relationship in MySQL” article.

2. Hibernate Model Class

Create two model classes – Stock.java and StockDetail.java, to represent the above tables.

File : Stock.java


package com.mkyong.stock;

public class Stock implements java.io.Serializable {

	private Integer stockId;
	private String stockCode;
	private String stockName;
	private StockDetail stockDetail;

	//constructor & getter and setter methods
	
}

File : StockDetail.java


package com.mkyong.stock;

public class StockDetail implements java.io.Serializable {

	private Integer stockId;
	private Stock stock;
	private String compName;
	private String compDesc;
	private String remark;
	private Date listedDate;

	//constructor & getter and setter methods

}

3. Hibernate XML Mapping

Now, create two Hibernate mapping files (hbm) – Stock.hbm.xml and StockDetail.hbm.xml.

File : Stock.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 25 April 2011 7:52:33 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
	<class name="com.mkyong.stock.Stock" table="stock" catalog="mkyongdb">
		<id name="stockId" type="java.lang.Integer">
			<column name="STOCK_ID" />
			<generator class="identity" />
		</id>
		<property name="stockCode" type="string">
			<column name="STOCK_CODE" length="10" not-null="true" unique="true" />
		</property>
		<property name="stockName" type="string">
			<column name="STOCK_NAME" length="20" not-null="true" unique="true" />
		</property>
		<one-to-one name="stockDetail" class="com.mkyong.stock.StockDetail"
			cascade="save-update"></one-to-one>
	</class>
</hibernate-mapping>

File : StockDetail.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 25 April 2011 7:52:33 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
	<class name="com.mkyong.stock.StockDetail" table="stock_detail"
		catalog="mkyongdb">
		<id name="stockId" type="java.lang.Integer">
			<column name="STOCK_ID" />
			<generator class="foreign">
				<param name="property">stock</param>
			</generator>
		</id>
		<one-to-one name="stock" class="com.mkyong.stock.Stock"
			constrained="true"></one-to-one>
		<property name="compName" type="string">
			<column name="COMP_NAME" length="100" not-null="true" />
		</property>
		<property name="compDesc" type="string">
			<column name="COMP_DESC" not-null="true" />
		</property>
		<property name="remark" type="string">
			<column name="REMARK" not-null="true" />
		</property>
		<property name="listedDate" type="date">
			<column name="LISTED_DATE" length="10" not-null="true" />
		</property>
	</class>
</hibernate-mapping>
Note
The main difficulty in this one-to-one relationship is ensuring both are assigned the same primary key. In StockDetail.hbm.xml, a special foreign identifier generator is declared, it will know get the primary key value from STOCK table. With constrained=”true”, it ensure the Stock must exists.

4. Hibernate Configuration File

Puts Stock.hbm.xml and StockDetail.hbm.xml in your Hibernate configuration file, and also MySQL connection details.

File : hibernate.cfg.xml


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyongdb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <mapping resource="com/mkyong/stock/Stock.hbm.xml" />
    <mapping resource="com/mkyong/stock/StockDetail.hbm.xml" />
</session-factory>
</hibernate-configuration>

5. Run It

Run it, Hibernate will insert a row into the STOCK table and a row into the STOCK_DETAIL table.

File : App.java


package com.mkyong;

import java.util.Date;
import org.hibernate.Session;
import com.mkyong.stock.Stock;
import com.mkyong.stock.StockDetail;
import com.mkyong.util.HibernateUtil;

public class App {
	public static void main(String[] args) {
		System.out.println("Hibernate one to one (XML mapping)");
		Session session = HibernateUtil.getSessionFactory().openSession();

		session.beginTransaction();

		Stock stock = new Stock();

		stock.setStockCode("4715");
		stock.setStockName("GENM");

		StockDetail stockDetail = new StockDetail();
		stockDetail.setCompName("GENTING Malaysia");
		stockDetail.setCompDesc("Best resort in the world");
		stockDetail.setRemark("Nothing Special");
		stockDetail.setListedDate(new Date());

		stock.setStockDetail(stockDetail);
		stockDetail.setStock(stock);

		session.save(stock);
		session.getTransaction().commit();

		System.out.println("Done");
	}
}

Output


Hibernate one to one (XML mapping)
Hibernate: insert into mkyongdb.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: insert into mkyongdb.stock_detail 
(COMP_NAME, COMP_DESC, REMARK, LISTED_DATE, STOCK_ID) values (?, ?, ?, ?, ?)
Done
Hibernate Annotation
For one-to-one in Hibernate annotation, please refer to this example
Download it – Hibernate-one-to-one-xml-mapping.zip (10KB)

Reference

  1. Hibernate Documentation – one to one relationship

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
49 Comment threads
16 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
49 Comment authors
Insaf Innampri88yankVijay Kumar VermasammyChris Chang Recent comment authors
newest oldest most voted
John
Guest
John

I used the above said approach in my code for one-to-one relationship. Getting the following exception
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

Vijay Kumar Verma
Guest
Vijay Kumar Verma

Thanks for lovely tutorial 😉

pri88yank
Guest
pri88yank

When to use One-to-One vs Value type mapping i.e.

Above is from Hibernate doc

trackback
Hibernate Tutorials | Tutorials

[…] One-to-one relationship example A one-to-one relationship project demonstration. […]

Nani
Guest
Nani

Hello yong,

I am using the Oracle Database, when i downloaded the project and try to compile it, it is throwing the below exception

” Dialect does not support identity key generation”

i believe it is coming from this line

can you Please suggest what is the alternate for “identity” if i am using oracle.

Thanks
Nani

vinit
Guest
vinit

thanks for providing good tutorials.

suraj
Guest
suraj

how can i identify which is the database name in annotation example?
please reply soon.
please help mr.yong.

suraj
Guest
suraj

is it neccesary to use any XML(.cfg or .hbm) files in annotation example?

patsai
Guest
patsai

This example help me a lot. Thank you very much.

bilal haider
Guest
bilal haider

Thank u for A Very good article….
I am new in hibernate … can you please tell me why we are not saving the child table i.e stock detail table e.g session.save(stockDetail)?
waiting for your reply,,,,

Swamy K
Guest
Swamy K

Hi Yong,

Good tutorial to learn things practically and step by step.

Thanks a lot.

trackback
Hibernate – One-to-one relationship example (Annotation)

[…] this tutorial, it will reuse the entire infrastructure of the previous “Hibernate one to one relationship example – XML mapping” tutorial, enhance it to support […]

trackback
Hibernate – One-to-One example (Annotation)

[…] Author: mkyong In this tutorial, it will reuse the entire infrastructure of the previous “Hibernate one to one relationship example – XML mapping” tutorial, enhance it to support Hibernate / JPA […]

M Naeem Akhtar
Guest
M Naeem Akhtar

Hi Thanks to provide a very good platform for learning and practical excercise, this is very gud effort u are doing. Thanka a lot. I facing some problem, please help me to resolve. I am new with Maven. How to run a application generated by MAVEN, which has a main class. using eclipse or without eclipse. E.g I downloaded one hibernate example(one-to-one-relationship) converted it for eclipse project using maven eclipse command and imported the project inside eclipse. how i run the App.java main method? by using eclipse ide or by making a new jar file. As my imported project is… Read more »

Bilal Haider
Guest
Bilal Haider

your articles are really handy…….Please update the download link Download it – Hibernate-one-to-one-xml-mapping.zip (10KB)
thank u…..

Amritpal
Guest
Amritpal

i have problem running this Example but have continue problem

INFO: Configuration resource: /src/util/hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: /src/util/hibernate.cfg.xml not found
Exception in thread "main" java.lang.ExceptionInInitializerError
	at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:24)
	at util.HibernateUtil.(HibernateUtil.java:10)
	at util.App.main(App.java:14)
Caused by: org.hibernate.HibernateException: /src/util/hibernate.cfg.xml not found
	at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
	at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1402)
	at org.hibernate.cfg.Configuration.configure(Configuration.java:1424)
	at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
	... 2 more
Hibernate one to one (XML mapping)
Yogesh
Guest
Yogesh

please give the example with one toone with property-ref attribute.and in may2many why this scenarion doesnot make sense for cascade deleteor deleteall.

srinu
Guest
srinu

how to devlop the one-to-one relationship in oracledatabase.

bramha
Guest
bramha

I try this example, but at the end this gives me the error

integrity constraint (TEST.SYS_C00267812) violated – parent key not found

Since we save the STOCK object before the entry of the STOCK_DETAIL object.

please tell the solution.

Akki
Guest
Akki

Nice Explaination !!

sunil
Guest
sunil

hi,

thanks for nice explanation for one-to-one mapping…but iam getting error by trying above one-to-one relationship mapping.

error is :Exception in thread “main” org.hibernate.PropertyNotFoundException: Could not find a getter for stockId in class com.sunil.domain.StockDetail

please reply me…

sunil

Sumit
Guest
Sumit

Hi, That’s a very nice explanation. I was just going through the docs provided by hibernate and there I found that the fetch property for one on one mapping is optional and can take either select or join whereas FieldType is a enumeration which is having 2 enums, LAZY and EAGER.

Please clarify.

Thanks & regards,
Sumit

nisha
Guest
nisha

hey thanks for the code but i am getting an error:
“org.hibernate.id.IdentifierGenerationException:attempted to assign id from null one-to-one property”
Please help me

thanks
nisha

Angel
Guest
Angel

hello,

thanks this tutorial help me very well.

but i have a question….in my application user can create column at run time.but this is not configured in .cfg.xml………so how can i retrieve this new column ?

any help will appreciated.. Thanks……..

Vineet
Guest
Vineet

Are you still replying here. I have exactly the same mapping as you have mentioned. I am using Postgres. but I am getting the below exception, m stuck here totaly. please help SEVERE: Servlet.service() for servlet [blackboard] in context with path [/Blackboard] threw exception [Request processing failed; nested exception is java.lang.Exception: java.lang.NullPointerException] with root cause java.lang.NullPointerException at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:521) at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:3867) at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:100) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697) at com.peanuts.blackboard.database.dao.impl.StudentDAO.savenewStudent(StudentDAO.java:74) at com.peanuts.blackboard.database.dao.impl.StudentDAO$$FastClassByCGLIB$$28a91834.invoke() at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at com.peanuts.blackboard.database.dao.impl.StudentDAO$$EnhancerByCGLIB$$946d8675.savenewStudent() at com.peanuts.blackboard.bus.svc.impl.StudentManager.savenewStudent(StudentManager.java:36)… Read more »

steven
Guest
steven

Hi,
I would like to know how to map like 3 tables suppose user (user_id pk), person(person_name, user_id fk) and customer (person_name, user_id fk) in the one to one mapping. If not possible is there any other way to map

Joydeep Bhattacharya
Guest
Joydeep Bhattacharya

One small clarification needed

Stock object conatins stockdetails object … thats fine

but why StockDetails class is having Stock object … its redundant

I am trying without it and getting this exception

StaleStateException

any idea why am I getting it ?

If you need details I can share you the same

shinde
Guest
shinde

Hi, I used your pom.xml file, got below error: Missing: ---------- 1) hibernate-commons-annotations:hibernate-commons-annotations:jar:3.0.0.GA Try downloading the file manually from the project website. Then, install it using the command: mvn install:install-file -DgroupId=hibernate-commons-annotations -Dartifac tId=hibernate-commons-annotations -Dversion=3.0.0.GA -Dpackaging=jar -Dfile=/pat h/to/file Alternatively, if you host your own repository you can deploy the file there: mvn deploy:deploy-file -DgroupId=hibernate-commons-annotations -DartifactI d=hibernate-commons-annotations -Dversion=3.0.0.GA -Dpackaging=jar -Dfile=/path/ to/file -Durl=[url] -DrepositoryId=[id] Path to dependency: 1) com.mkyong.common:one-to-one:jar:1.0-SNAPSHOT 2) hibernate-commons-annotations:hibernate-commons-annotations:jar:3.0.0 .GA 2) hibernate-annotations:hibernate-annotations:jar:3.3.0.GA Try downloading the file manually from the project website. Then, install it using the command: mvn install:install-file -DgroupId=hibernate-annotations -DartifactId=hibe rnate-annotations -Dversion=3.3.0.GA -Dpackaging=jar -Dfile=/path/to/file Alternatively, if you host your own… Read more »

Ehsan
Guest
Ehsan

Hi Mkyong How to use rolleback in hibernate please find the code below. package com.hcl.collection.manytomany; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.hcl.collection.manytomany.Employee; public class ManytoMany { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SessionFactory sessionfac=new Configuration().configure("/com/hcl/collection/manytomany/manytomany_hibernate.cfg.xml").buildSessionFactory(); System.out.println("SessionFactory=========="+sessionfac); Session session = sessionfac.openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Set<Employee> employee=new HashSet<Employee>(); employee.add(new Employee("Ehsan","IT","9711295282")); employee.add(new Employee("Smith","Admin","999123456")); Company com=new Company("TCS","Noida",employee); Company com1=new Company("HCL","Delhi",employee); session.save(com); session.save(com1); transaction.commit(); } catch (HibernateException e) { e.printStackTrace(); } finally { transaction.rollback(); session.close(); }… Read more »

Shafaqat
Guest
Shafaqat

I have same scenario, i want to insert only 1 row, i have inserted the row successfully but i want to update the same row if user tries to add another row with same primary key id, i am getting primary key error “Cannot insert duplicate key”