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.
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
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.
Annotation | Modifier | Description |
@Entity | Marks a class as a Hibernate Entity (Mapped class) | |
@Table | Name | Maps 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. |
@Id | Marks this class field as a Primary Key column. | |
@GeneratedValue | Instructs database to generate a value for this field automatically. | |
@Column | Name | Maps this field with table column specified by name and uses the field name if name modifier is absent. |
@OneToOne and @JoinColumn | They are used together to specify a One-to-One Association and the Join column. | |
@Temporal | Must 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!
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
.
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.
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
.
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.
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
.
A new pop window will open where we will enter the package name as: 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
.
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
.
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
.
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
.
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
.
A new pop window will open and select the wizard as an XML file.
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.
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 theSQL
statements on the console
4. Run the Application
To run the Hibernate application, Right click on the AppMain
class -> Run As -> Java 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!
Below is the snapshot of MySQL Database after execution of the above program.
Author Table
Book Table
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.
You can download the full source code of this example here: Hibernate One2One Mapping
Not working.
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “org.hibernate.Session.getTransaction()” because “com.jcg.hibernate.one2one.mapping.AppMain.sessionObj” is null
at com.jcg.hibernate.one2one.mapping.AppMain.main(AppMain.java:51)