×
DocsConsole

DocsConsole

Hibernate OneToOne Association Example

By | | Updated : 2020-02-03 | Viewed : 437 times

Hibernate Many To One Example

In this post, we are going to learn about the OneToOne Association with detailed examples. Please refer the Github for more examples. To know more clearly about associations please refer to the remaining posts.

What is OneToOne Association?

OneToOne can be defined with the relation of Employee and EmployeeDetails. Here Employee should contain only one EmployeeDetails. So Employee's object should be mapped with only one Employee Details.

Hibernate-OneToOne-Association

Notice the above-given diagram. Here one employe should be mapped with only EmployeeDetails. The OneToOne association in hibernate can be accomplished by using Shared Primary Key, Foreign Key association and Common Join Table. We will learn all these types of techniques in this post. But if you want to the full-fledged examples you can refer the remaining posts in hibernate.

Jar Dependency Artifacts

The important dependencies for writing the OneToOne Association Example will be as given below.

Maven Dependencies for OneToOne Association
	<!-- Hibernate 5.4.3.Final -->
	 <dependency>
		 <groupId>org.hibernate</groupId>
	 	<artifactId>hibernate-core</artifactId>
	 	<version>${hibernate-core-version}</version>
	 </dependency>
	 
	 <!-- MySql Driver -->
	 <dependency>
		 <groupId>mysql</groupId>
		 <artifactId>mysql-connector-java</artifactId>
	 	<version>${mysql.connector.version}</version>
	 </dependency>

OneToOne With Shared Primary Key

Here we have defined the OneToOne relationship between Product and ProductDetails.

Annotation Example for Shared Primary key

Product.java
@Entity
@Table(name = "PRODUCT")
public class Product {

	// Remaining Properties
	@OneToOne(cascade = CascadeType.ALL)
	@PrimaryKeyJoinColumn
	private ProductDetails prodDetails;
	
	//Setters and getters
	

}
ProductDetails.java
@Entity
@Table(name = "PRODUCT_DETAILS")
public class ProductDetails {

	//Remaining Properties

	@OneToOne(mappedBy = "prodDetails")
	private Product product;
	
	//Setters and getters
}

Here we used @OneToOne(cascade = CascadeType.ALL) and @PrimaryKeyJoinColumn in Product Entity Class. @PrimaryKeyJoinColumn will be used combinedly with @OneToOne in case Shared Primary Key. That means when both related entities have same id then we should use the @PrimaryKeyJoinColumn.

And @OneToOne(mappedBy = "prodDetails") annotation is used in ProductDetails Entity class. mappedBy is used for making the association bidirectional. You might know about mappedBy property in @OneToOne annotation in the ProductDetails entity class. Because ProductDetails is not the Owner of the relationship. On another side which is not owing side of the relationship, we should use this mappedBy attribute to make a directional relationship.

XML based Example for Shared Primary Key

To know XML based example please notice the below given XML Configurations.

product.hbm.xml
<hibernate-mapping package="com.docsconsole.tutorials.hibernate5.entity">
	<class name="Product" table="product">
	
		// Properties configuration
		<one-to-one name="prodDet" cascade="all" class="ProductDetails"></one-to-one>
	</class>
</hibernate-mapping>
productDetails.hbm.xml
<hibernate-mapping package="com.docsconsole.tutorials.hibernate5.entity">

	<class name="ProductDetails" table="product_details">
		//Remaining Properties
		<one-to-one name="product" constrained="true" class="Product"></one-to-one>
	</class>
</hibernate-mapping>

Here we have configured the one-to-one in both entiteis. So when you execute the above examples the below-given queries will be triggered.

Queries Generated in OneToOne Example
Hibernate: insert into product (PROD_NAME, PROD_VENDOR) values (?, ?)
Hibernate: insert into product_details (PROD_NAME, PROD_DESC, PROD_PRICE) values (?, ?, ?)

OneToOne With Foreign Key

Another important way of creating a OneToOne relationship is Foreign Key. Here we should have to use the Foreign Key relataionship between two tables.

Please create ManyToOneTest.java file with below given code.
Right click on src/main/java 
--> New 
--> Click on Class 
--> Enter value for Package as docs.console.com and Enter value for Name ManyToOneTest.java.
ManyToOneTest.java
package docs.console.com;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import docs.console.com.model.State;
import docs.console.com.util.HibernateUtil;
import docs.console.com.model.Cities;

public class ManyToOneTest {
	public static void main(String[] args) {

		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		try {
			Cities city = new Cities(40000, "hyderabad");
			session.save(city);
			
			State state = new State(50000, "A.P", city);
			session.save(state);

			session.getTransaction().commit();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
	}
}

The created project architecture will be as given below.

Hibernate Many To One

If we execute the ManyToOneTest.java then we will get below given output.

Hibernate Many To One Result
Leave A Reply