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 :
- Hibernate 3.6.3.Final
- MySQL 5.1.15
- Maven 3.0.3
- Eclipse 3.6
Project Structure
See the final project structure of this tutorial.
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.
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>
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
For one-to-one in Hibernate annotation, please refer to this example

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?
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.
I forgot asking for the way to save a stock without stock_detail. Thanks.
I like your way of explanation.
why can’t we use JDBC batch updates with HQL queries? not related to this one to one but looking for this
Hi MkYong,
How to make xml one to one association with composite key having different column names in parent and child table.
Regards,
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.
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
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
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. !
Very good tutorial ! simple and easy to understand ~ many thanks !
Thanks it really helpful to me. i like all your tutorials.
in hibernate model page is bean class or pojo class ?
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 .
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
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.
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”
Hi Mkyong
How to use rolleback in hibernate please find the code below.
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 repository you can deploy the file there: mvn deploy:deploy-file -DgroupId=hibernate-annotations -DartifactId=hibern ate-annotations -Dversion=3.3.0.GA -Dpackaging=jar -Dfile=/path/to/file -Durl=[u rl] -DrepositoryId=[id] Path to dependency: 1) com.mkyong.common:one-to-one:jar:1.0-SNAPSHOT 2) hibernate-annotations:hibernate-annotations:jar:3.3.0.GA ---------- 2 required artifacts are missing. for artifact: com.mkyong.common:one-to-one:jar:1.0-SNAPSHOT from the specified remote repositories: central (http://repo1.maven.org/maven2), JBoss repository (http://repository.jboss.com/maven2/) [INFO] ------------------------------------------------------------------------ [INFO] For more information, run Maven with the -e switch [INFO] ------------------------------------------------------------------------ [INFO] Total time: 40 seconds [INFO] Finished at: Mon Jul 16 22:01:18 IST 2012 [INFO] Final Memory: 14M/111MOne 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
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
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)
at com.peanuts.blackboard.web.controller.admin.AdminAddUserController.onSubmit(AdminAddUserController.java:72)
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 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
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……..
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
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
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
did u solve ur problem?
u are missing getter and setter for one or more of your properties in your DTO(POJO) classes.
Nice Explaination !!
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.
how to devlop the one-to-one relationship in oracledatabase.
This concept is database dependency, may be the syntax is slightly different.
please give the example with one toone with property-ref attribute.and in may2many why this scenarion doesnot make sense for cascade deleteor deleteall.
i have problem running this Example but have continue problem
Did you build it with Maven?
your articles are really handy…….Please update the download link Download it – Hibernate-one-to-one-xml-mapping.zip (10KB)
thank u…..
File is deleted! No idea why? Thanks i have backup, uploaded to server again. Thanks for report this broken link.
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 giving refrence/class path error even project’s .class file has all Maven Repo refrence entries. So im enable to run it, please guide me.
Thankz a lot
Hi Yong,
Good tutorial to learn things practically and step by step.
Thanks a lot.
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,,,,
If you define Hibernate relationship property, a single “session.save(stock)” statement will save it to both tables automatically. Of course, it’s always depend on your use case.
This example help me a lot. Thank you very much.
is it neccesary to use any XML(.cfg or .hbm) files in annotation example?
Sorry for late reply, for annotation, there is no need to define .hbm file, but .cfg configuration is still required. You just need to tell Hibernate about your database properties :)
Please download the annotation version and compare with yours.
how can i identify which is the database name in annotation example?
please reply soon.
please help mr.yong.
Do not understand your use case, please explains in detail.
thanks for providing good tutorials.
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
You may need to use sequence for Oracle database.
See the Hibernate documentation for details
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id
Hello yong,
thanks for your reply
Thanks
Nani
welcome
Hello Nani,
You are using Oracle database, so you have use sequence generator but you are used Identity generator. That’s way You are getting that error. because Identity generator
is specific to MySQL only. It won’t be worked on any other Databases.