[增刪改查] 最簡單的 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、程式碼結構
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 介面
相關文章
- [增刪改查] 最規範的 JPA 一對多/多對一 CRUD 示例
- spring data jpa關聯查詢(一對一、一對多、多對多)Spring
- jpa一對多查詢
- JPA(3) 表關聯關係(多對一、一對多、多對多、一對一)
- Spring Data JPA 之 一對一,一對多,多對多 關係對映Spring
- 最簡單的sql語句(增刪改查統計)SQL
- 一起學Vue:CRUD(增刪改查)Vue
- spring data jpa 多對一聯表查詢Spring
- gorm 關係一對一,一對多,多對多查詢GoORM
- JPA中對映關係詳細說明(一對多,多對一,一對一、多對多)、@JoinColumn、mappedBy說明APP
- 第一個mybatis程式,實現增刪改查CRUDMyBatis
- CoreData - 簡單 增刪改查
- Spring Boot 入門系列(二十八) JPA 的實體對映關係,一對一,一對多,多對多關係對映!Spring Boot
- 寫一個簡單的Linkedlist,實現增刪改查
- Python中CRUD增刪改查教程Python
- mybatis的一對多,多對一,以及多對對的配置和使用MyBatis
- hibernate一對多、多對多的實體設計和配置檔案配置
- MyBatis表關聯 一對多 多對一 多對多MyBatis
- Mybatis【一對多、多對一、多對多】知識要點MyBatis
- Go實現對MySQL的增刪改查GoMySql
- layui+ssm簡單增刪改查UISSM
- spring-data-jpa一對多、多對多雙向關聯,查詢操作的時候進入死迴圈問題Spring
- #MyBatis多表查詢 #多對一、一對多的兩種實現方式 @FDDLCMyBatis
- mybatis一對多&&多對一處理MyBatis
- MyBatis07-(多對一、一對多)MyBatis
- Mybatis一對多、多對一處理MyBatis
- Mybatis09_一對一、一對多、多對多、延遲載入MyBatis
- Java實現簡單的增刪改查操作Java
- iOS CoreData (一) 增刪改查iOS
- 單表增刪改查
- Spring Boot整合Mybatis完成級聯一對多CRUD操作Spring BootMyBatis
- Mybatis-plus實現簡單增刪改查MyBatis
- 多對一處理 和一對多處理的處理
- IDEA SpringBoot-Mybatis-plus 實現增刪改查(CRUD)IdeaSpring BootMyBatis
- 基於多資料來源零程式碼同時生成多個資料庫CRUD增刪改查RESTful API介面資料庫RESTAPI
- Node+Vue實現對資料的增刪改查Vue
- node+express對本地檔案的增刪改查操作Express
- 使用Mongoose類庫實現簡單的增刪改查Go