Home » Enterprise Java » hibernate » Hibernate One to One Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Hibernate One to One Example

In simple terms, a One-to-One Association is similar to Many-to-One association with a difference that the column will be set as unique i.e. Two entities are said to be in a One-to-One relationship if one entity has only one occurrence in the other entity. For example, an address object can be associated with a single employee object. However, these relationships are rarely used in the relational table models and therefore, we won’t need this mapping too often.

In this tutorial, we will learn how to use Hibernate One-To-One Unidirectional mapping using annotation based configuration.
 
 

1. Introduction

In One-to-One association, the source entity has a field that references another target entity. The @OneToOne JPA annotation is used to map the source entity with the target entity.

Fig. 1: One-to-One Relationship Overview

Fig. 1: One-to-One Relationship Overview

The One-to-One association can be either unidirectional or bidirectional.

  • In unidirectional association, the source entity has a relationship field that refers to the target entity and the source entity’s table contains a Foreign Key that references the Primary Key of the associated table
  • In bi-directional association, each entity (i.e. source and target) has a relationship field that refers to each other and the target entity’s table contains a Foreign Key. The source entity must use the mappedBy attribute to define the Bidirectional One-to-One mapping

But before we move on, let’s understand the Hibernate and the Annotations.

1.1 Hibernate

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is Java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. It provides reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling
  • Framework provides option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML based configuration
Fig. 2: Hibernate Overview

Fig. 2: Hibernate Overview

1.2 Hibernate Annotations

  • Hibernate annotations is the newest way to define mappings without a use of an XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g. Class name defaults to Table name and field names defaults to column names

1.3 Reference Guide on Hibernate Annotations

Hibernate Annotations are based on the JPA 2 specification. All the JPA annotations are defined in the javax.persistence.* package. The basic JPA annotations of Hibernate that can be used in an entity are the ones below.

AnnotationModifierDescription
@EntityMarks a class as a Hibernate Entity (Mapped class)
@TableNameMaps this class with a database table specified by name modifier. If the name is not supplied it maps the class with a table having the same name as the class.
@IdMarks this class field as a Primary Key column.
@GeneratedValueInstructs database to generate a value for this field automatically.
@ColumnNameMaps this field with table column specified by name and uses the field name if name modifier is absent.
@OneToOne and @JoinColumnThey are used together to specify a One-to-One Association and the Join column.
@TemporalMust be used with a java.util.Date field to specify the actual SQL type of the column.

1.4 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.5 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let’s see how to implement One-to-One relationship in Hibernate using Annotation!

2. Hibernate One-to-One Mapping Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Hibernate One-to-One Mapping Application Project Structure

Fig. 3: Hibernate One-to-One Mapping Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project

Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location‘ will be selected. Select the ‘Create a simple project (skip archetype selection)‘ checkbox and just click on next button to proceed.

Fig. 5: Project Details

Fig. 5: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of the maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>HibernateOneToOneMapping</groupId>
	<artifactId>HibernateOneToOneMapping</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called tutorialDb with 2 tables: author and book. Note that, author and book tables exhibit a One-to-One relationship. Open MySQL terminal or workbench terminal and execute the script:

CREATE DATABASE IF NOT EXISTS tutorialDb;

USE tutorialDb;

CREATE TABLE author (
  author_id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(45) NOT NULL,
  email varchar(45) NOT NULL,
  PRIMARY KEY (author_id)
);
 
CREATE TABLE book (
  book_id int(11) NOT NULL AUTO_INCREMENT,
  title varchar(128) NOT NULL,
  description varchar(512) NOT NULL,
  published date NOT NULL,
  author_id int(11) NOT NULL,
  PRIMARY KEY (book_id),
  KEY author_fk (author_id),
  CONSTRAINT author_fk FOREIGN KEY (author_id) REFERENCES author (author_id)
);

If everything goes well, the tables will be shown in the MySQL workbench. Below diagram shows the Entity relationship between these tables where book table contains a Foreign Key referring to the author table.

Fig. 7: One-to-One Mapping

Fig. 7: One-to-One Mapping

3.2 Maven Dependencies

Here, we specify only two dependencies for Hibernate Core and MySQL Connector. Rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>HibernateOneToOneMapping</groupId>
	<artifactId>HibernateOneToOneMapping</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<dependencies>
		<!-- Hibernate 4.3.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.6.Final</version>
		</dependency>
		<!-- Mysql Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.3 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation

Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.hibernate.one2one.mapping.

Fig. 9: Java Package Name (com.jcg.hibernate.one2one.mapping)

Fig. 9: Java Package Name (com.jcg.hibernate.one2one.mapping)

Once the package is created in the application, we will need to create the model and implementation classes. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation

Fig. 10: Java Class Creation

A new pop window will open and enter the file name as Author. The owner entity class will be created inside the package: com.jcg.hibernate.one2one.mapping.

Fig. 11: Java Class (Author.java)

Fig. 11: Java Class (Author.java)

Repeat the step (i.e. Fig. 10) and enter the filename as Book. The target entity class will be created inside the package: com.jcg.hibernate.one2one.mapping.

Fig. 12: Java Class (Book.java)

Fig. 12: Java Class (Book.java)

Again, repeat the step listed in Fig. 10 and enter the file name as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.one2one.mapping.

Fig. 13: Java Class (AppMain.java)

Fig. 13: Java Class (AppMain.java)

3.3.1 Implementation of Owner Entity

Add the following code to it:

Author.java

package com.jcg.hibernate.one2one.mapping;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "author")
public class Author {

	@Id
	@GeneratedValue
	@Column(name = "author_id")
	private long id;

	@Column(name = "name")
	private String name;

	@Column(name = "email")
	private String email;

	public Author() { }

	public Author(String name, String email) {
		this.name = name;
		this.email = email;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}  
}

3.3.2 Implementation of Target Entity

Add the following code to it:

Book.java

package com.jcg.hibernate.one2one.mapping;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {

	@Id
	@GeneratedValue
	@Column(name = "book_id")
	private long id;

	@Column(name = "title")
	private String title;

	@Column(name = "description")
	private String description;

	@Column(name = "published")
	private Date publishedDate;

	@JoinColumn(name = "author_id")
	@OneToOne(cascade = CascadeType.ALL)
	private Author author;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Date getPublishedDate() {
		return publishedDate;
	}

	public void setPublishedDate(Date publishedDate) {
		this.publishedDate = publishedDate;
	}

	public Author getAuthor() {
		return author;
	}

	public void setAuthor(Author author) {
		this.author = author;
	}
}

3.3.3 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the database to perform the INSERT operation. Add the following code to it:

AppMain.java

package com.jcg.hibernate.one2one.mapping;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class AppMain {

	static Session sessionObj;
	static SessionFactory sessionFactoryObj;

	private static SessionFactory buildSessionFactory() {
		// Creating Configuration Instance & Passing Hibernate Configuration File
		Configuration configObj = new Configuration();
		configObj.configure("hibernate.cfg.xml");

		// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
		ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); 

		// Creating Hibernate SessionFactory Instance
		sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
		return sessionFactoryObj;
	}

	public static void main(String[] args) {
		System.out.println(".......Hibernate One To One Mapping Example.......\n");
		try {
			sessionObj = buildSessionFactory().openSession();
			sessionObj.beginTransaction();

			// Creating A Book Entity
			Book bookObj = new Book();
			bookObj.setTitle("Hibernate Made Easy");
			bookObj.setDescription("Simplified Data Persistence with Hibernate and JPA");
			bookObj.setPublishedDate(new Date());

			bookObj.setAuthor(new Author("Cameron Wallace McKenzie", "cameron.bckenzie@gmail.com"));

			// Persisting (Or Saving) The Book Entity To The Database
			sessionObj.save(bookObj);			

			// Committing The Transactions To The Database
			sessionObj.getTransaction().commit();

			System.out.println("\n.......Records Saved Successfully To The Database.......");
		} catch(Exception sqlException) {
			if(null != sessionObj.getTransaction()) {
				System.out.println("\n.......Transaction Is Being Rolled Back.......");
				sessionObj.getTransaction().rollback();
			}
			sqlException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}
}

3.4 Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml. Right click on src/main/resources folder, New -> Other.

Fig. 14: XML File Creation

Fig. 14: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 15: Wizard Selection

Fig. 15: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as HibernateOneToOneMapping/src/main/resources and enter the file name as hibernate.cfg.xml. Click Finish.

Fig. 16: hibernate.cfg.xml

Fig. 16: hibernate.cfg.xml

Once the file is created, we will include the database configuration and mapping classes details. Add the following code to it:

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>
		<!-- SQL Dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Database Connection Settings -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="show_sql">true</property>

		<!-- Specifying Session Context -->
		<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>

		<!-- Mapping With Model Class Containing Annotations -->
		<mapping class="com.jcg.hibernate.one2one.mapping.Book" />
		<mapping class="com.jcg.hibernate.one2one.mapping.Author" />
	</session-factory>
</hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database named tutorialDb and the Mapping classes to be loaded
  • We have also instructed Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a Hibernate SessionFactory object
  • show_sql tag will instruct the Hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right click on the AppMain class -> Run As -> Java Application.

Fig. 17: Run Application

Fig. 17: Run Application

5. Project Demo

On executing the AppMain class, you will see the records in author and book tables. Developers can debug the example and see what happens in the database after every step. Enjoy!

Fig. 18: Application Output

Fig. 18: Application Output

Below is the snapshot of MySQL Database after execution of the above program.

Author Table

Fig. 19: Author Table Records

Fig. 19: Author Table Records

Book Table

Fig. 20: Book Table Records

Fig. 20: Book Table Records

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for Hibernate One-To-One mapping example tutorial and I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Hibernate One-To-One Mapping.

Download
You can download the full source code of this example here: Hibernate One2One Mapping

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of