[增删改查] 最简单的 JPA 一对多/多对一 CRUD 设计

一、前言

1、之前写过很多 SpringBoot 使用 JPA 实现 dao 层的 CRUD:
[增删改查] SpringBoot+JPA+EasyUI+MySQL 基本 CURD
但基本都是单表的
2、而实际开发中,最常见的就是 一对多/多对一 的关系,
3、实现 JPA 多表的 CRUD 的方式主要有两种:
① 使另一个实体为另一个实体的属性,成对使用注解 @ManyToOne、@JoinColumn 就可以了,如:

    @ManyToOne
    @JoinColumn(name="webSiteId")
    private WebSite webSite; // 网站

② 另外一种就是,不使用上述的关系,直接绑定 Integer 类型的主外键即可,相对上面,简单多了,但是人为编写 Service/Controller 层 CRUD 容易出现逻辑不严谨的现象,下面会涉及到
如:

    @Column(name="department_id")
    private Integer departmentId; //学生的宿舍外键

二、代码

https://github.com/larger5/SpringBootJPA.git

1、代码结构

[增删改查] 最简单的 JPA 一对多/多对一 CRUD 设计_第1张图片

2、pom

①生成接口测试文档
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.7.0version>
        dependency>

        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.6.1version>
        dependency>
②MySQL、JPA、web
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
3、yml 全局配置文件
server:
  port: 80 #为了以后访问项目不用写端口号
  context-path: / #为了以后访问项目不用写项目名
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8  #解决中文乱码的问题
    username: root
    password: 123
  jpa: 
    hibernate:
      ddl-auto: update  #数据库同步代码
    show-sql: true      #dao操作时,显示sql语句

4、实体

①学生
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_student")
public class Student {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(length = 100,name="name")
    private String name;

    @Column(name="department_id")
    private Integer departmentId;

    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 Integer getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(Integer departmentId) {
        this.departmentId = departmentId;
    }

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

}
②宿舍
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;

    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() {
        super();
        // TODO Auto-generated constructor stub
    }

}

5、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 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> {

}

6、Controller

①学生
package com.cun.controller;

import java.util.ArrayList;
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;

/**
 * 主 Student CRUD
 * ==>和单表的 CRUD 异同:
 *      ① insert(同)
 *      ② update(同)
 *      ③ delete(同)
 *      ④ select(异):关联查询
 * @author linhongcun
 *
 */
@RestController
@RequestMapping("/student")
@EnableSwagger2
public class StudentController {

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 1、增
     * ①学生姓名
     * ②宿舍 id 
     * @param student
     */
    @PostMapping("/insert")
    public void insertStudent(Student student) {
        studentDao.save(student);
    }

    /**
     * 2、根据id获取一个学生信息(个人、宿舍)
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public Map getStudent(@PathVariable Integer id) {
        Map map = new HashMap();
        Student student = studentDao.findOne(id);
        // 这一步很关键
        Department department = departmentDao.findOne(student.getDepartmentId());
        map.put("student", student);
        map.put("department", department);
        return map;
    }

    /**
     * 3、删
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public void deleteStudentById(@PathVariable Integer id) {
        studentDao.delete(id);
    }

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

    /**
     * 5、全
     * @return
     */
    @GetMapping("/all")
    public List> getAllStudent() {
        List studentList = studentDao.findAll();
        List> list=new ArrayList>();
        for (int i = 0; i < studentList.size(); i++) {
            Map map1 = new HashMap();
            map1.put("student", studentList.get(i));
            map1.put("department", departmentDao.findOne(studentList.get(i).getDepartmentId()));
            list.add(map1);
        }
        return list;
    }

}
②宿舍
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;

/**
 * 副 Department CRUD
 * ==>和单表简单的 CURD 的异同:
 *      ① delete(异):有 id 作为 Student 的 departmentId 者不能删
 *      ② insert(同)
 *      ③ select(同)
 *      ④ update(同)
 * @author linhongcun
 *
 */
@EnableSwagger2
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private DepartmentDao departmentDao;

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

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

    /**
     * 3、删(优化)
     * @param id
     * @return 
     */
    @DeleteMapping("/delete/{id}")
    public Map deleteDepartment(@PathVariable Integer id) {
        Map map = new HashMap();
        // 以下两步很关键
        List studentsByDepartmentId = studentDao.getStudentsByDepartmentId(id);
        if (studentsByDepartmentId.size() == 0) {
            departmentDao.delete(id);
            map.put("status", true);
        } else {
            map.put("status", false);
        }
        return map;
    }

    /**
     * 4、全
     * @return
     */
    @GetMapping("/all")
    public List getAllDepartment() {
        return departmentDao.findAll();
    }

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

三、其他

1、Swagger 接口

[增删改查] 最简单的 JPA 一对多/多对一 CRUD 设计_第2张图片

你可能感兴趣的:([增删改查] 最简单的 JPA 一对多/多对一 CRUD 设计)