DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Trending

  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • How to Introduce a New API Quickly Using Micronaut
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  1. DZone
  2. Data Engineering
  3. Databases
  4. Introduction to Spring Data JPA - Part 5 Unidirectional One to One Relations

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.

By 
Vinu Sagar user avatar
Vinu Sagar
·
Apr. 22, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
28.6K Views

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.

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.
Hibernate tableYou can see the foreign key reference (address_id)  in the organization table.

Now let us write the code.

Organization Entity

Java
 




x
40


 
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
}
40

          


  @OneToOne(targetEntity = Address.class, cascade = CascadeType.ALL)   

  private Address address; are how you define a one-to-one mapping.

Address Entity

Java
 




xxxxxxxxxx
1
59


 
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
    public Long getId() {
18
        return this.id;
19
    }
20
    public void setId(Long id) {
21
        this.id = id;
22
    }
23
    public String getBuilding() {
24
        return this.building;
25
    }
26
    public void setBuilding(String building) {
27
        this.building = building;
28
    }
29
    public String getStreet() {
30
        return this.street;
31
    }
32
    public void setStreet(String street) {
33
        this.street = street;
34
    }
35
    public String getCity() {
36
        return this.city;
37
    }
38
    public void setCity(String city) {
39
        this.city = city;
40
    }
41
    public String getState() {
42
        return this.state;
43
    }
44
    public void setState(String state) {
45
        this.state = state;
46
    }
47
    public String getCountry() {
48
        return this.country;
49
    }
50
    public void setCountry(String country) {
51
        this.country = country;
52
    }
53
    public String getZipcode() {
54
        return this.zipcode;
55
    }
56
    public void setZipcode(String zipcode) {
57
        this.zipcode = zipcode;
58
    }
59
}



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
10


 
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> {
9
}
10

          



Organization Service

Java
 




xxxxxxxxxx
1
46


 
1
package com.notyfyd.service;
2

          
3
import com.notyfyd.entity.Organization;
4
import com.notyfyd.repository.AddressRepository;
5
import com.notyfyd.repository.OrganizationRepository;
6
import org.springframework.http.ResponseEntity;
7
import org.springframework.stereotype.Service;
8
import org.springframework.transaction.annotation.Transactional;
9

          
10
@Service
11
public class OrganizationService {
12
    private OrganizationRepository organizationRepository;
13
    private AddressRepository addressRepository;
14

          
15
    public OrganizationService(OrganizationRepository organizationRepository, AddressRepository addressRepository) {
16
        this.organizationRepository = organizationRepository;
17
        this.addressRepository = addressRepository;
18
    }
19

          
20
    @Transactional
21
    public ResponseEntity<Object> createOrganization(Organization organization) {
22
        Organization org = new Organization();
23
        org.setName(organization.getName());
24
        org.setOrgId(organization.getOrgId());
25
        org.setAddress(organization.getAddress());
26
        Organization savedOrg = organizationRepository.save(org);
27
        if(organizationRepository.findById(savedOrg.getId()).isPresent())
28
            return ResponseEntity.ok().body("Organization created successfully.");
29
        else return ResponseEntity.unprocessableEntity().body("Failed to create the organization specified.");
30
    }
31

          
32
    @Transactional
33
    public ResponseEntity<Object> updateOrganization(Long id, Organization org) {
34
        if(organizationRepository.findById(id).isPresent()) {
35
            Organization organization = organizationRepository.findById(id).get();
36
            organization.setName(org.getName());
37
            organization.setOrgId(org.getName());
38
            addressRepository.deleteById(organization.getAddress().getId());
39
            organization.setAddress(org.getAddress());
40
            Organization savedOrganization = organizationRepository.save(organization);
41
            if(organizationRepository.findById(savedOrganization.getId()).isPresent())
42
                return ResponseEntity.ok().body("Successfully Updated Organization");
43
            else return ResponseEntity.unprocessableEntity().body("Failed to update the specified Organization");
44
        } else return ResponseEntity.unprocessableEntity().body("The specified Organization is not found");
45
    }
46
}



UPDATE Operation ( updateOrganization  method)

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.

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

          
51
}
52

          


We are using  @PutMapping  for the  UPDATE  operation. 

Run the application. Open Postman and send in the requests.

CREATE - JSON Object 

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

JSON
 




xxxxxxxxxx
1
11


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


Use  PUT  to send the request and a success message is returned.

Please find the source code here.

Modified UPDATE method

Java
 




xxxxxxxxxx
1
21


 
1
@Transactional
2
public ResponseEntity<Object> updateOrganization(Long id, Organization org) {
3
    if(organizationRepository.findById(id).isPresent()) {
4
        Organization organization = organizationRepository.findById(id).get();
5
        organization.setName(org.getName());
6
        organization.setOrgId(org.getName());
7
        Address address = addressRepository.findById(organization.getAddress().getId()).get();
8
        address.setBuilding(organization.getAddress().getBuilding());
9
        address.setStreet(organization.getAddress().getStreet());
10
        address.setCity(organization.getAddress().getCity());
11
        address.setState(organization.getAddress().getState());
12
        address.setCountry(organization.getAddress().getCountry());
13
        address.setZipcode(organization.getAddress().getZipcode());
14
        Address savedAddress =  addressRepository.save(address);
15
        organization.setAddress(savedAddress);
16
        Organization savedOrganization = organizationRepository.save(organization);
17
        if(organizationRepository.findById(savedOrganization.getId()).isPresent())
18
            return ResponseEntity.ok().body("Successfully Updated Organization");
19
        else return ResponseEntity.unprocessableEntity().body("Failed to update the specified Organization");
20
    } else return ResponseEntity.unprocessableEntity().body("The specified Organization is not found");
21
}


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:


Relational database Database Spring Data Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Manage Hierarchical Data in MongoDB With Spring
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • CRUD Operations on Deeply Nested Comments: Scalable Spring Boot and Spring Data approach

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!