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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
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

Insaf Innam
Guest
Insaf Innam

thank you very much for your explanation

pri88yank
Guest
pri88yank

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

Above is from Hibernate doc

Vijay Kumar Verma
Guest
Vijay Kumar Verma

Thanks for lovely tutorial ;)

Chris Chang
Guest
Chris Chang

Hi,Mr. Yang:

Errors message follow?
F:??ALTRunALTRun>mvn archetype:generate -DgroupId=com.javaweb.maven -Dar

tifactId=MavenDemo -DarchetypeArtifactId=maven-archetype-quickstart -Dinte
ractiveMode=false
[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ————————————————————————
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) > generate-sources
@ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) < generate-sources
@ standalone-pom << [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginResoluti
onException

saitej
Guest
saitej

Can I use Hibernate Template with different Database with same Hibernate Template bean with different Session Factory……?

pappy cami
Guest
pappy cami

very good tutorial for the beginer like me … Thank’s a lot

raju muddana
Guest
raju muddana

Add search feture to his site!!!

malavika
Guest
malavika

Hello..
I’m able to insert row in one table but not into the other one which was referenced from the primary key..Can you help me?

Vijay
Guest
Vijay

hi I too got the same problem, after adding cascade=”all” in student mapping file the data gets inserted into both tables.

jmegonzalez
Guest
jmegonzalez

Hi,

In this example, it has been forced to exist the detail row for every stock?
Or, by the other side, only it has been created one detail row for every stock with detail elements?

What would happen if the Stock object will have a null stock detail?

Thank you for your help!

Regards.

jmegonzalez
Guest
jmegonzalez

I forgot asking for the way to save a stock without stock_detail. Thanks.

venkateswarlu
Guest
venkateswarlu

I like your way of explanation.

sujit
Guest
sujit

why can’t we use JDBC batch updates with HQL queries? not related to this one to one but looking for this

Naresh
Guest
Naresh

Hi MkYong,

How to make xml one to one association with composite key having different column names in parent and child table.
Regards,
Naresh

Naresh
Guest
Naresh

Detailed explanation for the above posted question.
I have two tables with composite id having one to one relationship.
Table One : PK Columns : column1, column2
Table Two : PK Columns : column3, column4.
Columns are having different names. I have to map column1 – column3 and column2-column4.
How to give one to one association in xml configuration.

Reddy
Guest
Reddy

HI,

Getting below exception while executing the above code.
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`test/stock`, CONSTRAINT `FK68AF7162457E2F` FOREIGN KEY (`STOCK_ID`) REFERENCES `practice`.`stock_detail` (`STOCK_ID`))

Regards,
Udaykiran M

srinivas
Guest
srinivas

CAN YOU PLEASE EXPLAIN ME HOW DO STOCK_ID US GETTING INSERTED EVEN WHEN WE ARE NOT SETING THORUGH ManytoMany CLASS?

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

Dilip
Guest
Dilip

You made this concept so simple and easy to understand! i really liked the way u have explained. with the table structure and the entire hbm file, my doubts are all cleared. !

gary au
Guest
gary au

Very good tutorial ! simple and easy to understand ~ many thanks !

Madhu
Guest
Madhu

Thanks it really helpful to me. i like all your tutorials.

Shubhrajyoti satpathy
Guest
Shubhrajyoti satpathy

in hibernate model page is bean class or pojo class ?

Viraj
Guest
Viraj

How to make this project independent from database. Using “Identity” will need MySQL database. If we want to migrate to oracle then we should use sequences .

meysam
Guest
meysam

hi.i have got this when running this example in “Intellij Idea” IDE :
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/collections/map/LRUMap
at org.hibernate.util.SimpleMRUCache.init(SimpleMRUCache.java:71)
at org.hibernate.util.SimpleMRUCache.(SimpleMRUCache.java:55)
at org.hibernate.engine.query.QueryPlanCache.(QueryPlanCache.java:76)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:239)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
at HibernateUtil.(HibernateUtil.java:14)
at MainClass.main(MainClass.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:115)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.map.LRUMap
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
… 13 more

Process finished with exit code 1
i wonder if you help me to resolve this error
thank’s

satya marrapu
Guest
satya marrapu

Hi yong,

Your’s ideas are very helpful to me to learn new technologies. I’m very thankful that.

I have one doubt. I want to store multiple records at a time that means in a single transaction. if I use save() method , I can perform only single row functions only.But i want to store multiple records.

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”

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 »
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 »
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

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

Pawan
Guest
Pawan

hi Yong,

how can we use hibernate with JNDI ?

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 »
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……..

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

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