suchen
HeimJavajavaLernprogrammBeherrschen Sie bidirektionale Eins-zu-Eins-Beziehungen in Schritten: Steigern Sie die JPA-Effizienz von Spring Data

Unlocking the Power of Bidirectional One-to-One Relations

In this in-depth guide, we'll explore the intricacies of mutual one-to-one associations, CRUD operations, and the role of mappedBy, @JsonManagedReference, and @JsonBackReference in efficient data modeling.

  • Understanding Mutual One-to-One Associations
  • Streamlining CRUD Operations
  • The Importance of mappedBy
  • Demystifying @JsonManagedReference
  • Unlocking the Potential of @JsonBackReference

Through a concise example, we'll demonstrate how to seamlessly integrate these concepts, starting with entity definition.

Let's begin by modeling our entities.Master Bidirectional One-to-One Relations in teps: Boost Spring Data JPA EfficiencyNext, we'll examine how Hibernate generates the tables.

Master Bidirectional One-to-One Relations in teps: Boost Spring Data JPA EfficiencyIn this example, we've designated Address as the owning side of the one-to-one relationship, with Organization as the referencing side. This approach ensures that the foreign key relationship is established in both the address and organization tables. Now, let's delve into the code. We'll utilize the mappedBy attribute in conjunction with the @OneToOne annotation to define this relationship. The mappedBy attribute specifies the referencing side of the relationship, indicating to Hibernate that the relationship’s key resides on the other side. To master bidirectional one-to-one relations and unlock Spring Data JPA's full potential, visit t8tech.com.

Organization Entity

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

Institutional Address Entity

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 = "address")

private Organization organization;

In this particular scenario, the mappedBy attribute is invariably set to “parent”, implying that Address will assume the role of the owning side, while Organization will serve as the inverse reference.

Address Repository Module

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<address long> {
}
</address>

Organization Repository Module

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<organization long> {
}
</organization>

Address Management Controller

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

Organization Management Controller

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);
    }
}

Comprehensive Organizational Assistance Program

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

Configuring the Application

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

Now, let’s initiate the application. Open Postman and create a new organization using the JSON object provided below.

You can access the source code for this project at https://github.com/gudpick/jpa-demo/tree/one-to-one-bidirectional-starter.

{<br>

Das obige ist der detaillierte Inhalt vonBeherrschen Sie bidirektionale Eins-zu-Eins-Beziehungen in Schritten: Steigern Sie die JPA-Effizienz von Spring Data. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Top 4 JavaScript -Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript -Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

Dieser Artikel analysiert 2025 die vier besten JavaScript -Frameworks (React, Angular, Vue, Svelte) und verglichen ihre Leistung, Skalierbarkeit und Zukunftsaussichten. Während alle aufgrund starker Gemeinschaften und Ökosysteme dominant bleiben, sind ihr relatives Popul

Spring Boot Snakeyaml 2.0 CVE-2022-1471 Problem behobenSpring Boot Snakeyaml 2.0 CVE-2022-1471 Problem behobenMar 07, 2025 pm 05:52 PM

Dieser Artikel befasst sich mit der Verwundbarkeit von CVE-2022-1471 in Snakeyaml, einem kritischen Fehler, der die Ausführung von Remote-Code ermöglicht. Es wird beschrieben

Wie implementiere ich mehrstufige Caching in Java-Anwendungen mit Bibliotheken wie Koffein oder Guava-Cache?Wie implementiere ich mehrstufige Caching in Java-Anwendungen mit Bibliotheken wie Koffein oder Guava-Cache?Mar 17, 2025 pm 05:44 PM

In dem Artikel wird in der Implementierung von mehrstufigem Caching in Java mithilfe von Koffein- und Guava-Cache zur Verbesserung der Anwendungsleistung erläutert. Es deckt die Einrichtungs-, Integrations- und Leistungsvorteile sowie die Bestrafung des Konfigurations- und Räumungsrichtlinienmanagements ab

Wie funktioniert der Klassenladungsmechanismus von Java, einschließlich verschiedener Klassenloader und deren Delegationsmodelle?Wie funktioniert der Klassenladungsmechanismus von Java, einschließlich verschiedener Klassenloader und deren Delegationsmodelle?Mar 17, 2025 pm 05:35 PM

Mit der Klassenbelastung von Java wird das Laden, Verknüpfen und Initialisieren von Klassen mithilfe eines hierarchischen Systems mit Bootstrap-, Erweiterungs- und Anwendungsklassenloadern umfasst. Das übergeordnete Delegationsmodell stellt sicher

Node.js 20: wichtige Leistungssteigerung und neue FunktionenNode.js 20: wichtige Leistungssteigerung und neue FunktionenMar 07, 2025 pm 06:12 PM

Node.js 20 verbessert die Leistung durch V8 -Motorverbesserungen erheblich, insbesondere durch schnellere Müllsammlung und E/A. Zu den neuen Funktionen gehören eine bessere Support von WebAssembly und raffinierte Debugging -Tools, die Produktivität der Entwickler und die Anwendungsgeschwindigkeit.

ICEBERG: Die Zukunft von Data Lake TabellenICEBERG: Die Zukunft von Data Lake TabellenMar 07, 2025 pm 06:31 PM

Iceberg, ein offenes Tabellenformat für große analytische Datensätze, verbessert die Leistung und Skalierbarkeit von Data Lake. Es befasst sich mit Einschränkungen von Parquet/ORC durch internes Metadatenmanagement und ermöglicht eine effiziente Schemaentwicklung, Zeitreisen, gleichzeitiger W

So teilen Sie Daten zwischen Schritten in der GurkeSo teilen Sie Daten zwischen Schritten in der GurkeMar 07, 2025 pm 05:55 PM

In diesem Artikel werden Methoden zum Austausch von Daten zwischen Gurkenschritten und dem Vergleich des Szenario -Kontextes, globalen Variablen, Argumentenübergabe und Datenstrukturen untersucht. Es betont Best Practices für Wartbarkeit, einschließlich präziser Kontextgebrauch, beschreibend

Wie kann ich funktionale Programmierungstechniken in Java implementieren?Wie kann ich funktionale Programmierungstechniken in Java implementieren?Mar 11, 2025 pm 05:51 PM

In diesem Artikel wird die Integration der funktionalen Programmierung in Java unter Verwendung von Lambda -Ausdrücken, Streams -API, Methodenreferenzen und optional untersucht. Es zeigt Vorteile wie eine verbesserte Lesbarkeit der Code und die Wartbarkeit durch SUKTIVE UND VERUSNAHMETALITÄT

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

AI Hentai Generator

AI Hentai Generator

Erstellen Sie kostenlos Ai Hentai.

Heißer Artikel

Heiße Werkzeuge

Sicherer Prüfungsbrowser

Sicherer Prüfungsbrowser

Safe Exam Browser ist eine sichere Browserumgebung für die sichere Teilnahme an Online-Prüfungen. Diese Software verwandelt jeden Computer in einen sicheren Arbeitsplatz. Es kontrolliert den Zugriff auf alle Dienstprogramme und verhindert, dass Schüler nicht autorisierte Ressourcen nutzen.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) ist eine PHP/MySQL-Webanwendung, die sehr anfällig ist. Seine Hauptziele bestehen darin, Sicherheitsexperten dabei zu helfen, ihre Fähigkeiten und Tools in einem rechtlichen Umfeld zu testen, Webentwicklern dabei zu helfen, den Prozess der Sicherung von Webanwendungen besser zu verstehen, und Lehrern/Schülern dabei zu helfen, in einer Unterrichtsumgebung Webanwendungen zu lehren/lernen Sicherheit. Das Ziel von DVWA besteht darin, einige der häufigsten Web-Schwachstellen über eine einfache und unkomplizierte Benutzeroberfläche mit unterschiedlichen Schwierigkeitsgraden zu üben. Bitte beachten Sie, dass diese Software

SublimeText3 Englische Version

SublimeText3 Englische Version

Empfohlen: Win-Version, unterstützt Code-Eingabeaufforderungen!

EditPlus chinesische Crack-Version

EditPlus chinesische Crack-Version

Geringe Größe, Syntaxhervorhebung, unterstützt keine Code-Eingabeaufforderungsfunktion

SublimeText3 Linux neue Version

SublimeText3 Linux neue Version

SublimeText3 Linux neueste Version