欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[增删改查] 最规范的 JPA 一对多/多对一 CRUD 示例

程序员文章站 2022-05-09 09:24:48
...

一、前言

1、多对一,一对多,都是一样的,反过来了而已。

2、之前写过一篇不使用主外键关系的多表 CRUD:
[增删改查] 最简单的 JPA 一对多/多对一 CRUD 设计
虽可以帮助新手快速使用 JPA,但是这样是不严谨的,特别是记录的删除,有了主外键关系就不会让你随意删除了。

3、其实,规范使用 JPA,还是很简单的。

二、代码

代码以及放到 github 上了:https://github.com/larger5/SpringBootJPAOM.git

1、代码结构

[增删改查] 最规范的 JPA 一对多/多对一 CRUD 示例

2、entity

① 学生
package com.cun.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "t_student")
public class Student {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(length = 100)
    private String name;

    @ManyToOne
    @JoinColumn(name="department_id") // 默认也为 department_id
    Department department;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    // JPA 必备
    public Student() {
        super();
    }

}
② 宿舍
package com.cun.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "t_department")
public class Department {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(length = 100)
    private String name;

    // 必注、必应主表 Student 属性 Department department;但是造成了JSON 死循环
//  @OneToMany(mappedBy="department") 
//  private Set<Student> students=new HashSet<Student>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

//  public Set<Student> getStudents() {
//      return students;
//  }
//
//  public void setStudents(Set<Student> students) {
//      this.students = students;
//  }

    // JPA 必备
    public Department() {
        super();
    }

}

3、dao

① 学生
package com.cun.dao;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.cun.entity.Student;

public interface StudentDao extends JpaRepository<Student, Integer> {

    @Query(value="select * from t_student where department_id=?1",nativeQuery=true)
    List<Student> getStudentsByDepartmentId(Integer id);
}
② 宿舍
package com.cun.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.cun.entity.Department;

public interface DepartmentDao extends JpaRepository<Department, Integer>{

}

4、Controller

① 学生
package com.cun.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cun.dao.StudentDao;
import com.cun.entity.Student;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 多表 CRUD 注意点:
 * ① Select:JPA findOne 会同时查询外键值对应表的记录的其他属性(优点)
 * ② Delete、Update、Insert 同单表 CRUD 
 * @author linhongcun
 *
 */
@RestController
@RequestMapping("/student")
@EnableSwagger2
public class StudentController {

    @Autowired
    private StudentDao studentDao;

    /**
     * 1、查
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Student getStudentById(@PathVariable Integer id) {
        return studentDao.findOne(id);
    }

    /**
     * 2、增
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public Student insertStudent(Student student) {
        studentDao.save(student);
        return student;
    }

    /**
     * 3、删
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Student deleteStudentById(@Valid @PathVariable Integer id, BindingResult bindingResult) {
        Student student = studentDao.findOne(id);
        studentDao.delete(id);
        return student;
    }

    /**
     * 4、改
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student updateStudent(Student student) {
        studentDao.save(student);
        return student;
    }

    /**
     * 5、全
     * @return
     */
    @GetMapping("/all")
    public List<Student> getAllStudents() {
        return studentDao.findAll();
    }
}
② 宿舍
package com.cun.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cun.dao.DepartmentDao;
import com.cun.dao.StudentDao;
import com.cun.entity.Department;
import com.cun.entity.Student;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 多表 CRUD 注意点:
 * ① Delete:宿舍的一条记录id作为学生外键属性值时不能删除
 * ② Insert、Update、Select 同单表 CRUD
 * @author linhongcun
 *
 */
@RestController
@RequestMapping("/department")
@EnableSwagger2
public class DepartmentController {

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private StudentDao studentDao; // 删除检查是否存在关系

    /**
     * 1、查
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Department getDepartmentById(@PathVariable Integer id) {
        return departmentDao.findOne(id);
    }

    /**
     * 2、删:这个要特别注意,其他的没什么好讲的
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteDeparmentById(@PathVariable Integer id) {
        Department department = departmentDao.findOne(id);
        Map<String, Object> map = new HashMap<String, Object>();
        List<Student> studentsByDepartmentId = studentDao.getStudentsByDepartmentId(id);
        if (studentsByDepartmentId.size() == 0) {
            departmentDao.delete(id);
            map.put("status", true);
            map.put("msg", "删除成功");
            map.put("data", department);
        } else {
            map.put("status", false);
            map.put("msg", "不能删除,因存在关联关系");
        }
        return map;
    }

    /**
     * 3、改
     * @param department
     * @return
     */
    @PutMapping("/update")
    public Department updateDepartment(Department department) {
        departmentDao.save(department);
        return department;
    }

    /**
     * 4、增
     * @param department
     * @return
     */
    @PostMapping("/insert")
    public Department insertDepartment(Department department) {
        departmentDao.save(department);
        return department;
    }

    /**
     * 5、全
     * @return
     */
    @GetMapping("/all")
    public List<Department> getAllDepartments() {
        return departmentDao.findAll();
    }

}

5、yml

server:
  port: 80 #为了以后访问项目不用写端口号
  context-path: / #为了以后访问项目不用写项目名
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8  #解决中文乱码的问题
    username: root
    password: 123
  jpa: 
    hibernate:
      ddl-auto: update  #数据库同步代码
    show-sql: true      #dao操作时,显示sql语句

6、pom

① Swagger 接口(可选)
        <!-- swagger生成接口API -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- 接口API生成html文档 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>
② JPA、MySQL、Web
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

三、其他

1、Swagger 测试接口

[增删改查] 最规范的 JPA 一对多/多对一 CRUD 示例

2、数据库自动生成主外键关系

[增删改查] 最规范的 JPA 一对多/多对一 CRUD 示例

3、JPA 单表 CRUD 的例子

[增删改查] SpringBoot+JPA+EasyUI+MySQL 基本 CURD

相关标签: jpa 多表