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 ...>
			<id>JBoss repository</id>
		<!-- MySQL database driver -->

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"
<!-- Generated 25 April 2011 7:52:33 PM by Hibernate Tools 3.4.0.CR1 -->
	<class name="com.mkyong.stock.Stock" table="stock" catalog="mkyongdb">
		<id name="stockId" type="java.lang.Integer">
			<column name="STOCK_ID" />
			<generator class="identity" />
		<property name="stockCode" type="string">
			<column name="STOCK_CODE" length="10" not-null="true" unique="true" />
		<property name="stockName" type="string">
			<column name="STOCK_NAME" length="20" not-null="true" unique="true" />
		<one-to-one name="stockDetail" class="com.mkyong.stock.StockDetail"

File : StockDetail.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated 25 April 2011 7:52:33 PM by Hibernate Tools 3.4.0.CR1 -->
	<class name="com.mkyong.stock.StockDetail" table="stock_detail"
		<id name="stockId" type="java.lang.Integer">
			<column name="STOCK_ID" />
			<generator class="foreign">
				<param name="property">stock</param>
		<one-to-one name="stock" class="com.mkyong.stock.Stock"
		<property name="compName" type="string">
			<column name="COMP_NAME" length="100" not-null="true" />
		<property name="compDesc" type="string">
			<column name="COMP_DESC" not-null="true" />
		<property name="remark" type="string">
			<column name="REMARK" not-null="true" />
		<property name="listedDate" type="date">
			<column name="LISTED_DATE" length="10" not-null="true" />
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"
    <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" />

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();
		Stock stock = new Stock();
		StockDetail stockDetail = new StockDetail();
		stockDetail.setCompName("GENTING Malaysia");
		stockDetail.setCompDesc("Best resort in the world");
		stockDetail.setRemark("Nothing Special");
		stockDetail.setListedDate(new Date());


Hibernate one TO one (XML mapping)
Hibernate: INSERT INTO mkyongdb.stock (STOCK_CODE, STOCK_NAME) VALUES (?, ?)
Hibernate: INSERT INTO mkyongdb.stock_detail 
Hibernate Annotation
For one-to-one in Hibernate annotation, please refer to this example
Download it – Hibernate-one-to-one-xml-mapping.zip (10KB)


  1. Hibernate Documentation – one to one relationship
Tags :

About the Author

Founder of Mkyong.com and HostingCompass.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.


  • 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

  • pappy cami

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

  • raju muddana

    Add search feture to his site!!!

  • malavika

    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?

  • jmegonzalez


    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!


    • jmegonzalez

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

  • venkateswarlu

    I like your way of explanation.

    • sujit

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

  • Naresh

    Hi MkYong,

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

    • 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


    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`))

    Udaykiran M

  • srinivas



    Hibernate one TO one (XML mapping)
    Hibernate: INSERT INTO mkyongdb.stock (STOCK_CODE, STOCK_NAME) VALUES (?, ?)
    Hibernate: INSERT INTO mkyongdb.stock_detail

  • 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. !

  • http://www.garyau.com gary au

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

  • Madhu

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

  • Shubhrajyoti satpathy

    in hibernate model page is bean class or pojo class ?

  • 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

    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

  • 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

    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

    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(&quot;/com/hcl/collection/manytomany/manytomany_hibernate.cfg.xml&quot;).buildSessionFactory();
    		Session session = sessionfac.openSession(); 
    		Transaction transaction = null; 
    		try { 
    		transaction = session.beginTransaction(); 
            Set&lt;Employee&gt; employee=new HashSet&lt;Employee&gt;();
    		employee.add(new Employee(&quot;Ehsan&quot;,&quot;IT&quot;,&quot;9711295282&quot;));
    		employee.add(new Employee(&quot;Smith&quot;,&quot;Admin&quot;,&quot;999123456&quot;));
    		Company com=new Company(&quot;TCS&quot;,&quot;Noida&quot;,employee);
    		Company com1=new Company(&quot;HCL&quot;,&quot;Delhi&quot;,employee);
    		} catch (HibernateException e) { 
    		} finally { 
    		//ArrayList emp=com.getEmployee();
    	//	Iterator&lt;Employee&gt;itr=emp.iterator();
    			Employee emplo=itr.next();
  • shinde

    I used your pom.xml file, got below error:

    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
      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
    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:
    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/111M
  • http://www.scodz.com 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


    any idea why am I getting it ?

    If you need details I can share you the same

  • steven

    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

    • http://www.mkyong.com Pawan

      hi Yong,

      how can we use hibernate with JNDI ?

  • 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
    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)

  • Angel


    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

    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


  • 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,

  • sunil


    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…


    • Vineet

      did u solve ur problem?

      u are missing getter and setter for one or more of your properties in your DTO(POJO) classes.

  • Akki

    Nice Explaination !!

  • 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.

  • srinu

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

    • http://www.mkyong.com mkyong

      This concept is database dependency, may be the syntax is slightly different.

  • 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.

  • 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)
    • http://www.mkyong.com mkyong

      Did you build it with Maven?

  • Bilal Haider

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

    • http://www.mkyong.com mkyong

      File is deleted! No idea why? Thanks i have backup, uploaded to server again. Thanks for report this broken link.

  • M Naeem Akhtar

    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

  • Pingback: Hibernate – One-to-One example (Annotation)()

  • Pingback: Hibernate – One-to-one relationship example (Annotation)()

  • Swamy K

    Hi Yong,

    Good tutorial to learn things practically and step by step.

    Thanks a lot.

  • 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,,,,

    • http://www.mkyong.com mkyong

      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.

  • patsai

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

  • suraj

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

    • http://www.mkyong.com mkyong

      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.

  • suraj

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

    • http://www.mkyong.com mkyong

      Do not understand your use case, please explains in detail.

  • vinit

    thanks for providing good tutorials.

  • http://www.java2s.com 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.


    • http://www.mkyong.com mkyong

      You may need to use sequence for Oracle database.

      identity – supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

      sequence – uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

      See the Hibernate documentation for details

      • http://java2s.com Nani

        Hello yong,

        thanks for your reply


        • http://www.mkyong.com mkyong


    • satya marrapu

      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.

  • Pingback: Hibernate Tutorials | Tutorials()