[增刪改查] 最簡單的 JPA 一對多/多對一 CRUD 設計

IT小村發表於2018-04-04

一、前言

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、程式碼結構

這裡寫圖片描述

2、pom

①生成介面測試文件
        <!-- 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>
②MySQL、JPA、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>
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<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> {

}

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<String, Object> getStudent(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        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<Map<String, Object>> getAllStudent() {
        List<Student> studentList = studentDao.findAll();
        List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
        for (int i = 0; i < studentList.size(); i++) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            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<String, Object> deleteDepartment(@PathVariable Integer 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);
        } else {
            map.put("status", false);
        }
        return map;
    }

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

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

三、其他

1、Swagger 介面

這裡寫圖片描述

相關文章