Introduction to Spring Data JPA - Part 6 Bidirectional One to One Relations
The next article in this series introduces you to bidirectional one-to-one relations in Spring Data.
Join the DZone community and get the full member experience.Join For Free
Bidirectional One-to-One Relations
We will discuss the following:
- Bidirectional One-to-One Relations.
- CRUD Operations
We will do a small implementation incorporating all of the above.
We will start by modeling the entities.
Let us see how the tables are created by Hibernate.
I have made Address the owner of the one-to-one relation and Organization as the referencing side; otherwise, you could have found the foreign key relation only in the address table, not in the organization table. Let us see how it translates to code. We will be using
mappedBy with the
@OnetoOne annotation to define this.
mappedBy is used to define the referencing side of the relationship. It tells Hibernate that the key of the relationship lies on the other side.
@OneToOne(targetEntity = Organization.class, mappedBy = "address")
private Organization organization;
It is always
mappedBy = parent, so Address will be the owner and Organization will be the child reference.
Let us run the application. Open Postman and create the Organization. Please find the JSON Object below.
Please find the source code at https://github.com/gudpick/jpa-demo/tree/one-to-one-bidirectional-starter
When you send in the POST request you will see that the tables are populated correctly. The
GET request will give you a stack overflow error. Previously, we dealt with it when we used
@JsonIgnore to rectify this circular reference. Let us try
@JsonBackReference to rectify this error.
Please find the code snippets below.
@JsonManagedReference is used on the child reference and
@JsonBackReference is used in the corresponding child class (Organization). They handle the circular reference.
Now you can run the application making the changes. You will see that everything is working fine.
Please find the source code at https://github.com/gudpick/jpa-demo/tree/json-managed-reference
Please find the video tutorials below.
Opinions expressed by DZone contributors are their own.