{{announcement.body}}
{{announcement.title}}

Introduction to Spring Data JPA - Part 6 Bidirectional One to One Relations

DZone 's Guide to

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.

· Cloud Zone ·
Free Resource

Bidirectional 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.
Modeling tablesLet us see how the tables are created by Hibernate.

Hibernate tablesI 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

Java
 




x
39


1
package com.notyfyd.entity;
2
 
          
3
import javax.persistence.*;
4
 
          
5
@Entity
6
@Table(name = "t_organization")
7
public class Organization {
8
    @Id
9
    @GeneratedValue(strategy = GenerationType.IDENTITY)
10
    private Long id;
11
    private String name;
12
    private String orgId;
13
    @OneToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
14
    private Address address;
15
    public Long getId() {
16
        return this.id;
17
    }
18
    public void setId(Long id) {
19
        this.id = id;
20
    }
21
    public String getName() {
22
        return this.name;
23
    }
24
    public void setName(String name) {
25
        this.name = name;
26
    }
27
    public String getOrgId() {
28
        return this.orgId;
29
    }
30
    public void setOrgId(String orgId) {
31
        this.orgId = orgId;
32
    }
33
    public Address getAddress() {
34
        return this.address;
35
    }
36
    public void setAddress(Address address) {
37
        this.address = address;
38
    }
39
}


Address Entity

Java
 




xxxxxxxxxx
1
69


 
1
package com.notyfyd.entity;
2
 
          
3
import javax.persistence.*;
4
 
          
5
@Entity
6
@Table(name = "t_address")
7
public class Address {
8
    @Id
9
    @GeneratedValue(strategy = GenerationType.IDENTITY)
10
    private Long id;
11
    private String building;
12
    private String street;
13
    private String city;
14
    private String state;
15
    private String country;
16
    private String zipcode;
17
    @OneToOne(targetEntity = Organization.class, mappedBy = "address")
18
    private Organization organization;
19
    public Long getId() {
20
        return this.id;
21
    }
22
    public void setId(Long id) {
23
        this.id = id;
24
    }
25
    public String getBuilding() {
26
        return this.building;
27
    }
28
    public void setBuilding(String building) {
29
        this.building = building;
30
    }
31
    public String getStreet() {
32
        return this.street;
33
    }
34
    public void setStreet(String street) {
35
        this.street = street;
36
    }
37
    public String getCity() {
38
        return this.city;
39
    }
40
    public void setCity(String city) {
41
        this.city = city;
42
    }
43
    public String getState() {
44
        return this.state;
45
    }
46
    public void setState(String state) {
47
        this.state = state;
48
    }
49
    public String getCountry() {
50
        return this.country;
51
    }
52
    public void setCountry(String country) {
53
        this.country = country;
54
    }
55
    public String getZipcode() {
56
        return this.zipcode;
57
    }
58
    public void setZipcode(String zipcode) {
59
        this.zipcode = zipcode;
60
    }
61
 
          
62
    public Organization getOrganization() {
63
        return organization;
64
    }
65
 
          
66
    public void setOrganization(Organization organization) {
67
        this.organization = organization;
68
    }
69
}


  @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

Java
 




x


 
1
package com.notyfyd.repository;
2
 
          
3
import com.notyfyd.entity.Address;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.stereotype.Repository;
6
 
          
7
@Repository
8
public interface AddressRepository  extends JpaRepository<Address,Long> {
9
}


Organization Repository

Java
 




xxxxxxxxxx
1


 
1
package com.notyfyd.repository;
2
 
          
3
import com.notyfyd.entity.Organization;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.stereotype.Repository;
6
 
          
7
@Repository
8
public interface OrganizationRepository extends JpaRepository<Organization, Long> {


Address Controller

Java
 




xxxxxxxxxx
1


 
1
@RestController
2
public class AddressController {
3
    @Autowired
4
    private AddressRepository addressRepository;
5
    @GetMapping("/address/get/all")
6
    public List<Address> getAddress() {
7
        return addressRepository.findAll();
8
    }
9
}


Organization Controller

Java
 




xxxxxxxxxx
1
52


 
1
package com.notyfyd.controller;
2
 
          
3
import com.notyfyd.entity.Organization;
4
import com.notyfyd.repository.OrganizationRepository;
5
import com.notyfyd.service.OrganizationService;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.web.bind.annotation.*;
8
 
          
9
import java.util.List;
10
 
          
11
@RestController
12
public class OrganizationController {
13
    private OrganizationService organizationService;
14
    private OrganizationRepository organizationRepository;
15
 
          
16
    public OrganizationController(OrganizationService organizationService, OrganizationRepository organizationRepository) {
17
        this.organizationService = organizationService;
18
        this.organizationRepository = organizationRepository;
19
    }
20
 
          
21
    @PostMapping("/organization/create")
22
    public ResponseEntity<Object> createOrganization(@RequestBody Organization organization) {
23
        return organizationService.createOrganization(organization);
24
    }
25
    @DeleteMapping("/organization/delete/{id}")
26
    public ResponseEntity<Object> deleteOrganization(@PathVariable Long id) {
27
        if(organizationRepository.findById(id).isPresent()) {
28
            organizationRepository.deleteById(id);
29
            if (organizationRepository.findById(id).isPresent())
30
                return ResponseEntity.unprocessableEntity().body("Failed to delete the specified organization");
31
            else return ResponseEntity.ok("Successfully deleted the specified organization");
32
        } else return ResponseEntity.unprocessableEntity().body("Specified organization not present");
33
    }
34
    @GetMapping("/organization/get/{id}")
35
    public Organization getOrganization(@PathVariable Long id) {
36
        if(organizationRepository.findById(id).isPresent())
37
            return organizationRepository.findById(id).get();
38
        else return null;
39
    }
40
    @GetMapping("/organization/get")
41
    public List<Organization> getOrganizations() {
42
        return organizationRepository.findAll();
43
    }
44
 
          
45
    @PutMapping("/organization/update/{id}")
46
    public ResponseEntity<Object> updateOrganization(@PathVariable Long id, @RequestBody Organization org) {
47
        return organizationService.updateOrganization(id, org);
48
    }
49
}
50
 
          


Organization Service

Java
 




xxxxxxxxxx
1
54


 
1
package com.notyfyd.service;
2
 
          
3
import com.notyfyd.entity.Address;
4
import com.notyfyd.entity.Organization;
5
import com.notyfyd.repository.AddressRepository;
6
import com.notyfyd.repository.OrganizationRepository;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.stereotype.Service;
9
import org.springframework.transaction.annotation.Transactional;
10
 
          
11
@Service
12
public class OrganizationService {
13
    private OrganizationRepository organizationRepository;
14
    private AddressRepository addressRepository;
15
 
          
16
    public OrganizationService(OrganizationRepository organizationRepository, AddressRepository addressRepository) {
17
        this.organizationRepository = organizationRepository;
18
        this.addressRepository = addressRepository;
19
    }
20
 
          
21
    @Transactional
22
    public ResponseEntity<Object> createOrganization(Organization organization) {
23
        Organization org = new Organization();
24
        org.setName(organization.getName());
25
        org.setOrgId(organization.getOrgId());
26
        org.setAddress(organization.getAddress());
27
        Organization savedOrg = organizationRepository.save(org);
28
        if(organizationRepository.findById(savedOrg.getId()).isPresent())
29
            return ResponseEntity.ok().body("Organization created successfully.");
30
        else return ResponseEntity.unprocessableEntity().body("Failed to create the organization specified.");
31
    }
32
 
          
33
    @Transactional
34
    public ResponseEntity<Object> updateOrganization(Long id, Organization org) {
35
        if(organizationRepository.findById(id).isPresent()) {
36
            Organization organization = organizationRepository.findById(id).get();
37
            organization.setName(org.getName());
38
            organization.setOrgId(org.getName());
39
            Address address = addressRepository.findById(organization.getAddress().getId()).get();
40
            address.setBuilding(organization.getAddress().getBuilding());
41
            address.setStreet(organization.getAddress().getStreet());
42
            address.setCity(organization.getAddress().getCity());
43
            address.setState(organization.getAddress().getState());
44
            address.setCountry(organization.getAddress().getCountry());
45
            address.setZipcode(organization.getAddress().getZipcode());
46
            Address savedAddress =  addressRepository.save(address);
47
            organization.setAddress(savedAddress);
48
            Organization savedOrganization = organizationRepository.save(organization);
49
            if(organizationRepository.findById(savedOrganization.getId()).isPresent())
50
                return ResponseEntity.ok().body("Successfully Updated Organization");
51
            else return ResponseEntity.unprocessableEntity().body("Failed to update the specified Organization");
52
        } else return ResponseEntity.unprocessableEntity().body("The specified Organization is not found");
53
    }
54
}


application.properties

Properties files
 




xxxxxxxxxx
1


1
server.port=2003
2
spring.datasource.driver-class-name= org.postgresql.Driver
3
spring.datasource.url= jdbc:postgresql://192.168.64.6:30432/jpa-test
4
spring.datasource.username = postgres
5
spring.datasource.password = root
6
spring.jpa.show-sql=true
7
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

JSON
 




xxxxxxxxxx
1
12


 
1
{
2
    "name": "Nooble Academy",
3
    "orgId": "NAL",
4
    "address": {
5
        "building": "XII/706-A",
6
        "street": "Andheri",
7
        "city": "Mumbai",
8
        "state": "Maharashtra",
9
        "zipcode": "400703",
10
        "country": "India"
11
    }
12
}


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

Java
 




xxxxxxxxxx
1


 
1
@JsonManagedReference
2
@OneToOne(targetEntity = Organization.class, mappedBy = "address")
3
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

Java
 




xxxxxxxxxx
1


 
1
@JsonBackReference
2
@OneToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
3
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.



Topics:
cloud, database, jpa, microservices, oauth, spring boot, spring data jpa, spring security

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}