Introduction to Spring Data JPA - Part 5 Unidirectional One to One Relations
In the next article in this series, we take a look at unidirectional one-to-one relations with CRUD operations.
Join the DZone community and get the full member experience.Join For Free
Unidirectional One to One Relations
We will discuss the following:
- Unidirectional One to One Relations
- All CRUD Operations - CREATE, READ, UPDATE, DELETE
Let us model the entities. I have chosen different entities this time. Let us talk about the organization and address. Every organization will be associated with an address. So you can call it a one-to-one relation. Let us model the model entities as a unidirectional relation.
You can find a reference to address entity in the organization entity but no reference to the organization entity in the address entity, so we call it a unidirectional relation.
Now let us look at the default tables created by Hibernate.
You can see the foreign key reference
(address_id) in the organization table.
Now let us write the code.
@OneToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
private Address address; are how you define a one-to-one mapping.
UPDATE Operation (
Here, you find the organization by its Id, and you will use setters to set the name and organisation Id. We use the
findById method again to get the address. I am using the
delete method to delete the address, and then I am setting the new address with the setter method. Finally, the organization is saved. Since we are setting the cascade type to "ALL," the address is saved automatically. This way of updating brings up an issue. The primary key of the address will be changed. This might work for some cases but not a good practice. Let us correct this by modifying the update method.
We are using
@PutMapping for the
Run the application. Open Postman and send in the requests.
CREATE - JSON Object
When we send the request we will get that the organization is created successfully. You can use the
GET requests to verify the same. We have the API'S which gives all the the organization and also methods that gives you the organization given the ID.
UPDATE - JSON Object
PUT to send the request and a success message is returned.
Please find the source code here.
Modified UPDATE method
When we use this method the Id of the address will not get altered. You should try both and see the difference.
Please find source code at here.
Please find the video tutorials here:
Opinions expressed by DZone contributors are their own.