」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 輕鬆掌握雙向一對一關係:提升 Spring Data JPA 效率

輕鬆掌握雙向一對一關係:提升 Spring Data JPA 效率

發佈於2024-11-07
瀏覽:780

释放双向一对一关系的力量

在本深入指南中,我们将探讨相互一对一关联、CRUD 操作的复杂性,以及在高效数据建模中mappedBy、@JsonManagedReference 和 @JsonBackReference 的作用。

  • 理解相互的一对一关联
  • 简化 CRUD 操作
  • mappedBy 的重要性
  • 揭秘@JsonManagedReference
  • 释放@JsonBackReference的潜力

通过一个简洁的示例,我们将演示如何从实体定义开始无缝集成这些概念。

让我们首先对实体进行建模。Master Bidirectional One-to-One Relations in teps: Boost Spring Data JPA Efficiency接下来,我们将研究 Hibernate 如何生成表。

Master Bidirectional One-to-One Relations in teps: Boost Spring Data JPA Efficiency在此示例中,我们将 Address 指定为一对一关系的拥有方,将 Organization 指定为引用方。此方法可确保在地址表和组织表中都建立外键关系。现在,让我们深入研究代码。我们将利用mappedBy 属性与@OneToOne 注释结合起来定义这种关系。 mappedBy 属性指定关系的引用方,向 Hibernate 指示关系的键位于另一方。要掌握双向一对一关系并释放 Spring Data JPA 的全部潜力,请访问 t8tech.com。

组织实体

package com.notyfyd.entity;

import javax.persistence.*;

@Entity@Table(name = "t_organization")
public class Organization {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long entityId;
    private String companyName;
    private String organizationCode;
    @OneToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
    private Address headquarters;
    public Long getEntityId() {
        return this.entityId;
    }
    public void setEntityId(Long entityId) {
        this.entityId = entityId;
    }
    public String getCompanyName() {
        return this.companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public String getOrganizationCode() {
        return this.organizationCode;
    }
    public void setOrganizationCode(String organizationCode) {
        this.organizationCode = organizationCode;
    }
    public Address getHeadquarters() {
        return this.headquarters;
    }
    public void setHeadquarters(Address headquarters) {
        this.headquarters = headquarters;
    }
}

机构地址实体

package com.notyfyd.entity;

import javax.persistence.*;

@Entity@Table(name = "t_address")
public class Address {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String building;
    private String street;
    private String city;
    private String state;
    private String country;
    private String zipcode;
    @OneToOne(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 =“地址”)

私人组织;

在此特定场景中,mappedBy 属性始终设置为“parent”,这意味着 Address 将承担拥有方的角色,而 Organization 将充当反向引用。

地址存储库模块

package com.notyfyd.repository;

import com.notyfyd.entity.Address;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repositorypublic interface AddressRepository extends JpaRepository
{ }

组织存储库模块

package com.notyfyd.repository;

import com.notyfyd.entity.Organization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repositorypublic interface OrganizationRepository extends JpaRepository {
}

地址管理控制器

@RestControllerpublic class AddressController {
    @Autowired    private AddressRepository addressRepository;
    
    @GetMapping("/address/retrieve/all")    public List
retrieveAllAddresses() { return addressRepository.findAll(); } }

组织管理控制器

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;

@RestControllerpublic class OrganizationController {
    private OrganizationService organizationService;
    private OrganizationRepository organizationRepository;

    public OrganizationController(OrganizationService organizationService, OrganizationRepository organizationRepository) {
        this.organizationService = organizationService;
        this.organizationRepository = organizationRepository;
    }

    @PostMapping("/organization/create")    public ResponseEntity<Object> createOrganization(@RequestBody Organization organization) {
        return organizationService.createOrganization(organization);
    }
    @DeleteMapping("/organization/delete/{id}")    public ResponseEntity<Object> deleteOrganization(@PathVariable 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");
    }
    @GetMapping("/organization/get/{id}")    public Organization getOrganization(@PathVariable Long id) {
        if(organizationRepository.findById(id).isPresent())
            return organizationRepository.findById(id).get();
        else return null;
    }
    @GetMapping("/organization/get")    public List<Organization> getOrganizations() {
        return organizationRepository.findAll();
    }

    @PutMapping("/organization/update/{id}")    public ResponseEntity<Object> updateOrganization(@PathVariable Long id, @RequestBody Organization org) {
        return organizationService.updateOrganization(id, org);
    }
}

综合组织援助计划

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;

@Servicepublic class OrganizationService {
    private OrganizationRepository organizationRepository;
    private AddressRepository addressRepository;

    public OrganizationService(OrganizationRepository organizationRepository, AddressRepository addressRepository) {
        this.organizationRepository = organizationRepository;
        this.addressRepository = addressRepository;
    }

    @Transactional    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.");
    }

    @Transactional    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");
    }
}

配置应用程序

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

现在,让我们开始申请吧。打开 Postman 并使用下面提供的 JSON 对象创建一个新组织。

您可以在 https://github.com/gudpick/jpa-demo/tree/one-to-one-bi Direction-starter 访问该项目的源代码。

{
版本聲明 本文轉載於:https://dev.to/emilyjohnsonready/master-bidirectional-one-to-one-relations-in-5-steps-boost-spring-data-jpa-efficiency-1m13?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3