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
Note
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;
 
@Entity
@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;
	}
 
	@Id
	@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;
 
@Entity
@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"))
	@Id
	@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)
	@PrimaryKeyJoinColumn
	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;
	}
 
	@Temporal(TemporalType.DATE)
	@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"
"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 class="com.mkyong.stock.Stock" />
    <mapping class="com.mkyong.stock.StockDetail" />
</session-factory>
</hibernate-configuration>

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();
 
		session.beginTransaction();
 
		Stock stock = new Stock();
 
		stock.setStockCode("7052");
		stock.setStockName("PADINI");
 
		StockDetail stockDetail = new StockDetail();
		stockDetail.setCompName("PADINI Holding Malaysia");
		stockDetail.setCompDesc("one stop shopping");
		stockDetail.setRemark("vinci vinci");
		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 (Annotation)
Hibernate: INSERT INTO mkyongdb.stock (STOCK_CODE, STOCK_NAME) VALUES (?, ?)
Hibernate: INSERT INTO mkyongdb.stock_detail 
(COMP_DESC, COMP_NAME, LISTED_DATE, REMARK, STOCK_ID) VALUES (?, ?, ?, ?, ?)
Done

Reference

  1. Hibernate Documentation – one to one relationship
Tags :

About the Author

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

Comments

  • Pingback: tv online, online tv()

  • Pingback: Blue Coaster33()

  • Mukul

    getting following error:

    java.lang.NullPointerException
    [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

    Hello,

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

    Can you reply it?

    Manu

  • 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

    Hi,

    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,
    ph.

  • Thierry

    Hi,

    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 :
    http://stackoverflow.com/questions/4653909/hibernate-jpa-onetoone-querying-despite-lazy-fetch

    But I didn’t make working yet…

    Best regards,
    Thierry

  • 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;
    try
    {

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

    Stock stock = new Stock();

    stock.setStockCode(“7052″);
    stock.setStockName(“PADINI”);

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

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

    entityManager.persist(stock);
    entityManager.getTransaction().commit();

    System.out.println(“Done”);

  • Sarath

    Hi,

    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.

    Regards,
    Sarath

  • 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
    http://javaworldwide.blogspot.in/2012/05/one-to-many-relationship-in-hibernate.html

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

    Regards,
    Usman

  • Atif

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

    Hi,

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