OneToOne Annotation in Spring Boot With Hibernate And Jpa

Arijit Sarkar
5 min readFeb 14, 2023

In this tutorial, we will learn how to implement a One-To-One relationship between entities using Hibernate and Jpa in Spring Boot using @OneToOne annotation.

1. What is One-To-One association

Before going into details of how to make relationships between entities in Hibernate, let’s first see how we make relationships between objects in JAVA. In JAVA, the association of objects is very simple: we use a class’s attribute (variable) to do so. Below is the definition of two simple classes, Factory and Product:

// Factory class 
public class Factory {
...
// Factory can make product
private Product product;
...
}
// Product class 
public class Product {
...
private String productName;
...
}

We have declared a Factory POJO with an attribute variable ( product) of the Product class. In JAVA, with attributes we can make a relation (associate) between the Factory class and the Product class.

A One-To-One relationship is to associate one JAVA object with another object. For example, a motorcycle has an engine and each engine belongs to a particular motorcycle, any location on the Earth must have a geolocation and the geolocation refers to a particular location.

Now if we think for a second how can we store the objects into a relational database. The traditional database stores the data in two-dimensional table format — in rows and columns and relationships are maintained between the tables using primary key and foreign key. But objects hold the data in variables and we can’t store the association of objects directly into the database table using our traditional JDBC APIs.

With the help of an Object-relational mapping (ORM) tool we can overcome this problem. One of the most popular ORM tools is Hibernate. Using Hibernate we can automate the process of saving the association of JAVA objects to database tables and access database table data and convert them into JAVA objects again. In Spring Boot, we use some special annotations to convert our plain JAVA class into a persistent class or entity and access and manipulate the data using Hibernate. To interact with relational databases, Hibernate has implemented JPA (JAVA Persistence API) and uses it for data manipulation. JPA is a specification that is defined by JAVA for object-relational mapping. With this specification, Hibernate provides us a collection of classes and methods for data persistence.

Now it is time to make our hands dirty. Let’s dive into coding.💪

2. Spring Boot project creation

Then click on GENERATE to download the project zip file. Unzip the zip file. Now import the project in Eclipse/STS as a Maven project.

3. Connect to Database

Here, we’ve set the datasource.url to our JDBC connection URL. The datasource.user and datasource.password are the credentials for the database.

It is not required to specify datasource.driver-class-name, because Spring Boot can gather the required information from the connection URL. But we will be on the safe side if we specify the driver-class-name.

The jpa.show-sql is used to show Hibernate sql queries in the console when application is running, jpa.hibernate.ddl-auto is set update — this will update the database schema every time we restart the application and hibernate.dialect indicates which database dialect we are using.

To demonstrate, we will create two entities: Motorcycle and Engine. Then create a One-To-One relationship between these two entities.

4. Entities

First, we will create the Engine entity with annotations to make it persistent.

As you can see, the Engine class is a simple JAVA class with some private variables, a constructor and some getter and setter, and an overridden toString() method. The main things to notice are that we have used some annotations (metadata about a class):@Entity, @Table, @Id, etc.

By using @Entity annotation we make a plain JAVA class into a persistent class.

@Table is for our database table with the name ( ENGINE).

@Id is used for defining the primary key (object identifier). In the Engine class, the primary key is defined as an Id variable.

@Column annotation is used for defining column names in the database table. If we want the column name of the database table to be different from that of the variable name ( Id), we must use this annotation.

We have added @GeneratedValue annotation to the Id variable. This annotation is used to specify the strategy to generate the value of the primary key ( id). We have used GenerationType.IDENTITY to the primary key — this is the same as AUTO_INCREMENT of MySQL.

So when we run the project, Hibernate will create a table named ENGINE, with primary key id ( AUTO_INCREMENT) and other columns with specified names.

Now, the Motorcycle entity with annotations:

In the persistent Motorcycle class, we have used some different annotations:@OneToOne, @JoinColumn.

@OneToOne annotation is used to associate one JAVA object with another JAVA object. In other words, if we try to describe it from the database perspective — one row of a particular table is exactly related to one row of another table and vice versa.

In this example, we are going to make a relationship between the Motorcycle and Engine. Here, one entity has a dependency on another entity in a relationship, in other words, without the Motorcycle there is no meaning of Engine. This is a cascading relationship. So, by specifying CascadeType.ALL, we can do INSERT, PERSIST, MERGE, DELETE, and REFRESH operations on both related entities at the same time.

@JoinColumn annotation is used to define a foreign key with the specified name ( engine_id).

So, Hibernate will join the MOTOR_CYCLE table and the ENGINE table with a foreign key named engine_id as we have mentioned Engine POJO as an attribute and the engine_id column will be created in the MOTOR_CYCLE table to store the primary key value ENGINE table.

5. Repository

In Spring Boot, the repository is the data access layer to interact with our real database for operations like insert, update, and delete using Spring Data JPA. As our MotorcycleRepository extends JpaRepository, we have significantly reduced the amount of boilerplate codes that are required to perform database operations.

Here is our MotorcycleRepository:

6. Controller

A controller is a public class with one or more public methods. By convention, controllers are placed in the Controller directory. In Spring Boot, if a class is annotated with@Controller or@RestController, that particular class will serve the role of a controller, and those public methods are exposed as HTTP endpoints as they are annotated with@PostMapping or @GetMapping.

So an HTTP GET request to http://localhost:{PORT}/{method-name} causes the@GetMapping method of the ExampleController class to be executed.

The following code snippet is for MotorcycleController:

……..

You can read the rest of the tutorial here.

Originally published at https://codenicetomedear.blogspot.com.

--

--