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 FreeBidirectional One-to-One Relations
We will discuss the following:
- Bidirectional One-to-One Relations.
- CRUD Operations
- mappedBy
- @JsonManagedReference
- @JsonBackReference.
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.
Organization Entity
package com.notyfyd.entity;
import javax.persistence.*;
name = "t_organization") (
public class Organization {
strategy = GenerationType.IDENTITY) (
private Long id;
private String name;
private String orgId;
targetEntity = Address.class, cascade = CascadeType.ALL) (
private Address address;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getOrgId() {
return this.orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address Entity
xxxxxxxxxx
package com.notyfyd.entity;
import javax.persistence.*;
name = "t_address") (
public class Address {
strategy = GenerationType.IDENTITY) (
private Long id;
private String building;
private String street;
private String city;
private String state;
private String country;
private String zipcode;
targetEntity = Organization.class, mappedBy = "address") (
private Organization organization;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getBuilding() {
return this.building;
}
public void setBuilding(String building) {
this.building = building;
}
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZipcode() {
return this.zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
@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.
Address Repository
package com.notyfyd.repository;
import com.notyfyd.entity.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
public interface AddressRepository extends JpaRepository<Address,Long> {
}
Organization Repository
xxxxxxxxxx
package com.notyfyd.repository;
import com.notyfyd.entity.Organization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
public interface OrganizationRepository extends JpaRepository<Organization, Long> {
Address Controller
xxxxxxxxxx
public class AddressController {
private AddressRepository addressRepository;
"/address/get/all") (
public List<Address> getAddress() {
return addressRepository.findAll();
}
}
Organization Controller
xxxxxxxxxx
package com.notyfyd.controller;
import com.notyfyd.entity.Organization;
import com.notyfyd.repository.OrganizationRepository;
import com.notyfyd.service.OrganizationService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
public class OrganizationController {
private OrganizationService organizationService;
private OrganizationRepository organizationRepository;
public OrganizationController(OrganizationService organizationService, OrganizationRepository organizationRepository) {
this.organizationService = organizationService;
this.organizationRepository = organizationRepository;
}
"/organization/create") (
public ResponseEntity<Object> createOrganization( Organization organization) {
return organizationService.createOrganization(organization);
}
"/organization/delete/{id}") (
public ResponseEntity<Object> deleteOrganization( Long id) {
if(organizationRepository.findById(id).isPresent()) {
organizationRepository.deleteById(id);
if (organizationRepository.findById(id).isPresent())
return ResponseEntity.unprocessableEntity().body("Failed to delete the specified organization");
else return ResponseEntity.ok("Successfully deleted the specified organization");
} else return ResponseEntity.unprocessableEntity().body("Specified organization not present");
}
"/organization/get/{id}") (
public Organization getOrganization( Long id) {
if(organizationRepository.findById(id).isPresent())
return organizationRepository.findById(id).get();
else return null;
}
"/organization/get") (
public List<Organization> getOrganizations() {
return organizationRepository.findAll();
}
"/organization/update/{id}") (
public ResponseEntity<Object> updateOrganization( Long id, Organization org) {
return organizationService.updateOrganization(id, org);
}
}
Organization Service
xxxxxxxxxx
package com.notyfyd.service;
import com.notyfyd.entity.Address;
import com.notyfyd.entity.Organization;
import com.notyfyd.repository.AddressRepository;
import com.notyfyd.repository.OrganizationRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
public class OrganizationService {
private OrganizationRepository organizationRepository;
private AddressRepository addressRepository;
public OrganizationService(OrganizationRepository organizationRepository, AddressRepository addressRepository) {
this.organizationRepository = organizationRepository;
this.addressRepository = addressRepository;
}
public ResponseEntity<Object> createOrganization(Organization organization) {
Organization org = new Organization();
org.setName(organization.getName());
org.setOrgId(organization.getOrgId());
org.setAddress(organization.getAddress());
Organization savedOrg = organizationRepository.save(org);
if(organizationRepository.findById(savedOrg.getId()).isPresent())
return ResponseEntity.ok().body("Organization created successfully.");
else return ResponseEntity.unprocessableEntity().body("Failed to create the organization specified.");
}
public ResponseEntity<Object> updateOrganization(Long id, Organization org) {
if(organizationRepository.findById(id).isPresent()) {
Organization organization = organizationRepository.findById(id).get();
organization.setName(org.getName());
organization.setOrgId(org.getName());
Address address = addressRepository.findById(organization.getAddress().getId()).get();
address.setBuilding(organization.getAddress().getBuilding());
address.setStreet(organization.getAddress().getStreet());
address.setCity(organization.getAddress().getCity());
address.setState(organization.getAddress().getState());
address.setCountry(organization.getAddress().getCountry());
address.setZipcode(organization.getAddress().getZipcode());
Address savedAddress = addressRepository.save(address);
organization.setAddress(savedAddress);
Organization savedOrganization = organizationRepository.save(organization);
if(organizationRepository.findById(savedOrganization.getId()).isPresent())
return ResponseEntity.ok().body("Successfully Updated Organization");
else return ResponseEntity.unprocessableEntity().body("Failed to update the specified Organization");
} else return ResponseEntity.unprocessableEntity().body("The specified Organization is not found");
}
}
application.properties
xxxxxxxxxx
server.port=2003
spring.datasource.driver-class-name= org.postgresql.Driver
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
spring.datasource.username = postgres
spring.datasource.password = root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
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
xxxxxxxxxx
{
"name": "Nooble Academy",
"orgId": "NAL",
"address": {
"building": "XII/706-A",
"street": "Andheri",
"city": "Mumbai",
"state": "Maharashtra",
"zipcode": "400703",
"country": "India"
}
}
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 @JsonManagedRefrence
and @JsonBackReference
to rectify this error.
Please find the code snippets below.
Address Entity
xxxxxxxxxx
targetEntity = Organization.class, mappedBy = "address") (
private Organization organization;
@JsonManagedReference
is used on the child reference and @JsonBackReference
is used in the corresponding child class (Organization). They handle the circular reference.
Organization Entity
xxxxxxxxxx
targetEntity = Address.class, cascade = CascadeType.ALL) (
private Address address;
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.
Comments