[增刪改查] 最規範的 JPA 一對多/多對一 CRUD 示例

IT小村發表於2018-04-04

一、前言

1、多對一,一對多,都是一樣的,反過來了而已。

2、之前寫過一篇不使用主外來鍵關係的多表 CRUD:
[增刪改查] 最簡單的 JPA 一對多/多對一 CRUD 設計
雖可以幫助新手快速使用 JPA,但是這樣是不嚴謹的,特別是記錄的刪除,有了主外來鍵關係就不會讓你隨意刪除了。

3、其實,規範使用 JPA,還是很簡單的。

二、程式碼

程式碼以及放到 github 上了:https://github.com/larger5/SpringBootJPAOM.git

1、程式碼結構

這裡寫圖片描述

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 測試介面

這裡寫圖片描述

2、資料庫自動生成主外來鍵關係

這裡寫圖片描述

3、JPA 單表 CRUD 的例子

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

相關文章