Using @OneToOne annotation in JPA

In JPA, to express one relationship to another, for example, a tourist can have a single room in a large hotel, we will use the @OneToOne annotation. How is it in details? In this tutorial, let’s learn about annotation @OneToOne in JPA!

First, I will create a Maven project as an example:

Using @OneToOne annotation in JPA

I will use Hibernate as JPA implementation so I will add Hibernate dependency as follows:

MySQL Connector:

Suppose, I now have two tables including a tourist and a room with the following information:

As you can see, the room table has three columns: id, name and hotel with the primary key is the id column. The tourist table has columns: id, name and room_id with the primary key is id column. In the tourist table, I have defined a foreign key from the tourist table to the room table so that a tourist will be in a room and a room can only have a tourist in it.

Entity for the above tables using the @OneToOne annotation would look like below:

Entity Tourist:

Entity Room:

Because the tourist table has a column room_id which is a foreign key to the room table then in the Tourist entity, we will declare the @OneToOne annotation along with another annotation @JoinColumn to represent this relationship.

To show the opposite relationship, a room with only one tourist, I also used the @OneToOne annotation in the Room entity with the mappedBy property as room. The room attribute here is the variable name in the Tourist entity declared with the @OneToOne annotation.

OK, so we’ve finished declaring the @OneToOne annotation to show the relationship between a tourist and a room. Now let’s take an example to see how it works.

I will add the configuration file for JPA, persistence.xml, located in the /src/main/resources/META-INF directory with the following contents:

Suppose in the database, we have following data:

Using @OneToOne annotation in JPA

then when running the following example:

the result will be:

Using @OneToOne annotation in JPA


Add Comment