【Spring Boot 3】【JPA】@ManyToOne 实现一对多单向关联

【Spring Boot 3】【JPA】@ManyToOne 实现一对多单向关联

背景

软件开发是一门实践性科学,对大多数人来说,学习一种新技术不是一开始就去深究其原理,而是先从做出一个可工作的DEMO入手。但在我个人学习和工作经历中,每次学习新技术总是要花费或多或少的时间、检索不止一篇资料才能得出一个可工作的DEMO,这占用了我大量的时间精力。因此本文旨在通过一篇文章即能还原出可工作的、甚至可用于生产的DEMO,期望初学者能尽快地迈过0到1的这一步骤,并在此基础上不断深化对相关知识的理解。
为达以上目的,本文会将开发环境、工程目录结构、开发步骤及源码尽量全面地展现出来,文字描述能简则简,能用代码注释的绝不在正文中再啰嗦一遍,正文仅对必要且关键的信息做重点描述。

介绍

《【Spring Boot 3】【JPA】一对多单向关联》 说明了开发Spring Boot应用时如何使用 @OneToMany 注解处理一对多关联关系,但是因为 @OneToMany 无法控制获取记录的数量,存在内存溢出的风险,因此日常开发中多数情况下会使用 @ManyToOne 注解处理一对多关联关系。

本文介绍开发Spring Boot应用时如何使用 @ManyToOne 注解处理一对多单向关联关系,涵盖 主从双数据表带有中间关联关系表的三数据表 这两种存储关联关系的实现。

本文定义了公司(Company)、工程师(Engineer)、经理(Manager)三个实体,其中公司(Company)与工程师(Engineer)、公司(Company)与经理(Manager)都是一对多单向关联,且关系主控方(即关系拥有方)都在 的一侧,即工程师(Engineer)和经理(Manager)。

开发环境

分类 名称 版本
操作系统 Windows Windows 11
JDK Oracle JDK 21.0.1
IDE IntelliJ IDEA 2023.2.4
构建工具 Apache Maven 3.9.3
数据库 MySQL 8.0.33

开发步骤及源码

1> 创建Maven工程,添加依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.jiyongliang</groupId>
        <artifactId>springboot3-jpa</artifactId>
        <version>0.0.1</version>
    </parent>
    <artifactId>springboot3-jpa-many-to-one</artifactId>

    <properties>
        <java.version>21</java.version>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot.version>3.2.2</spring-boot.version>
        <mysql-connector-j.version>8.3.0</mysql-connector-j.version>
        <flyway.version>10.6.0</flyway.version>
        <lombok.version>1.18.30</lombok.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactI
  • 12
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是 Spring Boot JPA 实现一对多增删改查的示例代码: 1. 创建实体类 ``` @Entity public class Parent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true) private List<Child> children = new ArrayList<>(); // getters and setters } @Entity public class Child { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") private Parent parent; // getters and setters } ``` 2. 创建 Repository 接口 ``` public interface ParentRepository extends JpaRepository<Parent, Long> { } ``` 3. 创建 Service 类 ``` @Service public class ParentService { @Autowired private ParentRepository parentRepository; public Parent save(Parent parent) { return parentRepository.save(parent); } public void delete(Long id) { parentRepository.deleteById(id); } public Parent findById(Long id) { return parentRepository.findById(id).orElse(null); } public List<Parent> findAll() { return parentRepository.findAll(); } } ``` 4. 创建 Controller 类 ``` @RestController @RequestMapping("/parents") public class ParentController { @Autowired private ParentService parentService; @PostMapping public Parent create(@RequestBody Parent parent) { return parentService.save(parent); } @PutMapping("/{id}") public Parent update(@PathVariable Long id, @RequestBody Parent parent) { Parent existingParent = parentService.findById(id); if (existingParent == null) { throw new RuntimeException("Parent not found"); } existingParent.setName(parent.getName()); existingParent.setChildren(parent.getChildren()); return parentService.save(existingParent); } @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { parentService.delete(id); } @GetMapping("/{id}") public Parent findById(@PathVariable Long id) { return parentService.findById(id); } @GetMapping public List<Parent> findAll() { return parentService.findAll(); } } ``` 以上就是 Spring Boot JPA 实现一对多增删改查的示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

又言又语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值