Hibernate – One-to-One example (Annotation)

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

Project Structure

See the final project structure of this tutorial.

project structure
Since Hibernate 3.6, annotation codes are merged into the Hibernate core module, so, the “previous pom.xml file can be reuse.

1. “One-to-one” table relationship

See the previous one to one table relationship again.

one to one relationship

2. Hibernate Model Class

Create two model classes – Stock.java and StockDetail.java, and put the annotation code inside.

File : Stock.java

package com.mkyong.stock;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Table(name = "stock", catalog = "mkyongdb", uniqueConstraints = {
		@UniqueConstraint(columnNames = "STOCK_NAME"),
		@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
	private Integer stockId;
	private String stockCode;
	private String stockName;
	private StockDetail stockDetail;
	public Stock() {
	public Stock(String stockCode, String stockName) {
		this.stockCode = stockCode;
		this.stockName = stockName;
	public Stock(String stockCode, String stockName, StockDetail stockDetail) {
		this.stockCode = stockCode;
		this.stockName = stockName;
		this.stockDetail = stockDetail;
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "STOCK_ID", unique = true, nullable = false)
	public Integer getStockId() {
		return this.stockId;
	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
	public String getStockCode() {
		return this.stockCode;
	public void setStockCode(String stockCode) {
		this.stockCode = stockCode;
	@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
	public String getStockName() {
		return this.stockName;
	public void setStockName(String stockName) {
		this.stockName = stockName;
	@OneToOne(fetch = FetchType.LAZY, mappedBy = "stock", cascade = CascadeType.ALL)
	public StockDetail getStockDetail() {
		return this.stockDetail;
	public void setStockDetail(StockDetail stockDetail) {
		this.stockDetail = stockDetail;

File : StockDetail.java

package com.mkyong.stock;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Table(name = "stock_detail", catalog = "mkyongdb")
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;
	public StockDetail() {
	public StockDetail(Stock stock, String compName, String compDesc,
			String remark, Date listedDate) {
		this.stock = stock;
		this.compName = compName;
		this.compDesc = compDesc;
		this.remark = remark;
		this.listedDate = listedDate;
	@GenericGenerator(name = "generator", strategy = "foreign", 
	parameters = @Parameter(name = "property", value = "stock"))
	@GeneratedValue(generator = "generator")
	@Column(name = "STOCK_ID", unique = true, nullable = false)
	public Integer getStockId() {
		return this.stockId;
	public void setStockId(Integer stockId) {
		this.stockId = stockId;
	@OneToOne(fetch = FetchType.LAZY)
	public Stock getStock() {
		return this.stock;
	public void setStock(Stock stock) {
		this.stock = stock;
	@Column(name = "COMP_NAME", nullable = false, length = 100)
	public String getCompName() {
		return this.compName;
	public void setCompName(String compName) {
		this.compName = compName;
	@Column(name = "COMP_DESC", nullable = false)
	public String getCompDesc() {
		return this.compDesc;
	public void setCompDesc(String compDesc) {
		this.compDesc = compDesc;
	@Column(name = "REMARK", nullable = false)
	public String getRemark() {
		return this.remark;
	public void setRemark(String remark) {
		this.remark = remark;
	@Column(name = "LISTED_DATE", nullable = false, length = 10)
	public Date getListedDate() {
		return this.listedDate;
	public void setListedDate(Date listedDate) {
		this.listedDate = listedDate;

3. Hibernate Configuration File

Puts annotated classes Stock.java and StockDetail.java 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 class="com.mkyong.stock.Stock" />
    <mapping class="com.mkyong.stock.StockDetail" />

4. 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 (Annotation)");
		Session session = HibernateUtil.getSessionFactory().openSession();
		Stock stock = new Stock();
		StockDetail stockDetail = new StockDetail();
		stockDetail.setCompName("PADINI Holding Malaysia");
		stockDetail.setCompDesc("one stop shopping");
		stockDetail.setRemark("vinci vinci");
		stockDetail.setListedDate(new Date());


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


  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.


  • Pingback: bottled alkaline water()

  • Pingback: water ionizer()

  • Pingback: pay per day loans plan()

  • Pingback: stop parking()

  • Pingback: alkaline water machine()

  • Pingback: laan penge billigt()

  • Pingback: xnxx()

  • Pingback: laan penge nu sms()

  • Pingback: parking()

  • Pingback: lan her og nu()

  • Pingback: DIRECTV packages()

  • Pingback: DIRECTV for your company()

  • Pingback: Google()

  • Pingback: kangen water()

  • Pingback: alkaline water()

  • Pingback: tv online, online tv()

  • Pingback: Blue Coaster33()

  • Mukul

    getting following error:

    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:521)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:3842)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:100)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.event.def.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:415)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.event.def.DefaultMergeEventListener.mergeTransientEntity(DefaultMergeEventListener.java:341)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.event.def.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:303)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:258)
    [9/20/13 18:14:38:411 IST] 0000002f SystemErr R at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:877)

  • Vaibhav

    Please also explain annotations it is difficult to understand without it.

  • Kaushik

    please can someone specifically tell which hibernate jar files are used because i am getting following error

    INFO: Configuration resource: /hibernate.cfg.xml
    Initial SessionFactory creation failed.org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
    Exception in thread “main” java.lang.ExceptionInInitializerError
    at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
    at util.HibernateUtil.(HibernateUtil.java:9)
    at mainclass.App.main(App.java:14)
    Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1692)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1647)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1626)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:213)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:46)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1600)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:201)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:46)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:183)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:46)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1506)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:177)
    at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)

    please do reply

  • Manuel Gnerlich


    I have performance problem with that. see: http://stackoverflow.com/questions/16713114/performance-issue-with-primarykeyjoincolumn

    Can you reply it?


  • RahamaTullah

    I am new to Hibernate , I started one application using spring with Hibernate annotations,
    I got strucked with errors, please guide me,
    Caused by: org.hibernate.MappingException: Could not determine type for:
    Actually I have one table in that I have two foreign keys, from two different tables,
    How can I map those two tables? please guide me, if u want anything more , please mail me,
    my mail id :[email protected]

  • bala

    I just use ur example in my project but data is not inserted

    could u help me on this

  • http://www.fnatic.com/users/HerthaSabirod66 Ehtel Hurm

    Hi there! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  • Peter Harvey


    I have the same question as Usman Awan. If the class stock has a member stockdetail, why
    does the class stockdetail need to have a stock member?

    thank you,

  • Thierry


    Thank you for your post and your good job on your site. It’s a pleasure to read you.

    I tried your example. It seems that lazy loading doesn’t work when reading step.
    I found this :

    But I didn’t make working yet…

    Best regards,

  • Tushar

    Great Job Mykong:)
    It is a very helpful post :)

  • Sai

    Can you do a one to one mapping between a Table and a View?

  • raky

    Great Job Mykong, i have tested the same code with hibernate 4.1,jpa 2,jboss eclipse plugin mysql, and it worked very well thank for sharing the same .

    EntityManagerFactory enityMgrFactry;
    EntityManager entityManager;
    EntityTransaction entityTrans;

    enityMgrFactry= Persistence.createEntityManagerFactory(“employeePersistenceUnit”);
    entityManager = enityMgrFactry.createEntityManager();

    Stock stock = new Stock();


    StockDetail stockDetail = new StockDetail();
    stockDetail.setCompName(“PADINI Holding Malaysia”);
    stockDetail.setCompDesc(“one stop shopping”);
    stockDetail.setRemark(“vinci vinci”);
    stockDetail.setListedDate(new Date());




  • Sarath


    The examples are so clear and much helpful.

    I have a query on annotations, in case a junit test case method requires db call(instead of a db call i will be using csv files for fetching/inserting data for junits) along with @test, is @transactional required or not.


  • Pingback: Hibernate annotations relations | Jisku.com - Developers Network()

  • http://javaworldwide.blogspot.in vishnu

    There are two ways to do one to one mapping in the Hibernate Using the annotation
    1. With Intermediate table.
    2. Without Intermediate table.

    For detail information see the below link

    • Pankaj Shinde

      plz check your link

    • Pankaj Shinde

      its for One to Many
      and not for One to One as u said.

  • Usman Awan

    Hi Mkyong,

    It is a very helpful post , Just have one question:

    Why did you make a property of Stock in StockDetail class, and upon saving you also did this:
    stock.setStockDetail(stockDetail); // this is ok for me that stock contain stockdetial
    stockDetail.setStock(stock); // now this is the question why stockDetail must have stock object?

    Waiting for your reply.


  • Atif

    Sorry for the double post ! cause it cut off some words …


    First i want to thank you for all your great posts !

    I have one question :
    I am wondering if it is enough to only add unique = true without using UniqueConstraint annotation …

    If you do so and if you add hibernate.hbm2ddl.auto (value:update), then hibernate creates for that field more than once ‘UNIQUE KEY’ !

    Best Regards,