Example One to one mapping

In this tutorial i will explain how establish relationship between two entity object. In last tutorials we have seen how to save entity object when there is a value object inside entity object or collection of value object inside entity object.

In this tutorial we will learn how to establish one to one relationship between two entity object.

one to one mappingHere is one to one mapping between student and course entity object. Here both the object are entity object.



@OneToOne annotation will tell hibernate that there is one to one relationship between course and student entities.

@JoinColumn(name=”courseId”) annotation is used to specify join column name. If we do not specify this name then hibernate will take default name for this column which is¬†courseOpted_courseId .Class name followed by primary key column name of that column.



When we run this program than hibernate will run following query.

Hibernate: insert into Student (courseId, regNumber, studentName) values (?, ?, ?)
Hibernate: insert into Course (courseDuration, courseName) values (?, ?)
Hibernate: update Student set courseId=?, regNumber=?, studentName=? where studentId=?

First it insert student object in table ,at this time it does not know course id. Then it insert course object. After that it update student record to update course id.

This is all in this post. In next post i will explain one to many and many to one relation .

About the Author: devender kumar

java/j2EE developer

Comments are closed.