[增刪改查] 最規範的 JPA 一對多/多對一 CRUD 示例
一、前言
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 的例子
相關文章
- [增刪改查] 最簡單的 JPA 一對多/多對一 CRUD 設計
- jpa一對多查詢
- spring data jpa關聯查詢(一對一、一對多、多對多)Spring
- JPA(3) 表關聯關係(多對一、一對多、多對多、一對一)
- Spring Data JPA 之 一對一,一對多,多對多 關係對映Spring
- 一起學Vue:CRUD(增刪改查)Vue
- gorm 關係一對一,一對多,多對多查詢GoORM
- JPA中對映關係詳細說明(一對多,多對一,一對一、多對多)、@JoinColumn、mappedBy說明APP
- spring data jpa 多對一聯表查詢Spring
- 第一個mybatis程式,實現增刪改查CRUDMyBatis
- Spring Boot 入門系列(二十八) JPA 的實體對映關係,一對一,一對多,多對多關係對映!Spring Boot
- MyBatis表關聯 一對多 多對一 多對多MyBatis
- mybatis的一對多,多對一,以及多對對的配置和使用MyBatis
- Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增刪改查示例Spring Boot
- Python中CRUD增刪改查教程Python
- Mybatis【一對多、多對一、多對多】知識要點MyBatis
- Go實現對MySQL的增刪改查GoMySql
- springboot(十五):springboot+jpa+thymeleaf增刪改查示例Spring Boot
- JPA(hibernate)一對多根據多的一方某屬性進行過濾查詢
- Mybatis一對多、多對一處理MyBatis
- mybatis一對多&&多對一處理MyBatis
- MyBatis07-(多對一、一對多)MyBatis
- #MyBatis多表查詢 #多對一、一對多的兩種實現方式 @FDDLCMyBatis
- 基於MyEclipse的Hibernate的多對一和一對多操作簡單示例Eclipse
- Mybatis09_一對一、一對多、多對多、延遲載入MyBatis
- mybatis入門基礎(六)----高階對映(一對一,一對多,多對多)MyBatis
- spring-data-jpa一對多、多對多雙向關聯,查詢操作的時候進入死迴圈問題Spring
- Hibernate多對多示例
- iOS CoreData (一) 增刪改查iOS
- Hibernate對單條記錄的增刪改查
- 使用Go語言建立簡單的CRUD增刪改查Go
- js對json格式物件增刪改查功能JSON物件
- Spring Boot整合Mybatis完成級聯一對多CRUD操作Spring BootMyBatis
- 多對一處理 和一對多處理的處理
- 基於多資料來源零程式碼同時生成多個資料庫CRUD增刪改查RESTful API介面資料庫RESTAPI
- Rails 一對多AI
- node+express對本地檔案的增刪改查操作Express
- Node+Vue實現對資料的增刪改查Vue