**1. 級操操作**
級操操作是指:操作對象A的同時,也操作該對象關聯的其他對象。
```java
//@OneToOne、@OneToMany、@ManyToOne、@ManyToMany 都有一個屬性 cascade 來控制級聯操作
public @interface OneToMany {
//配置級聯操作
//CascadeType.MERGE 級聯更新
//CascadeType.PERSIST 級聯保存
//CascadeType.REFRESH 級聯刷新
//CascadeType.REMOVE 級聯刪除
//CascadeType.ALL 所有級聯操作
CascadeType[] cascade() default {};
}
```
<br/>
**2. 使用級聯操作**
(1)建立實體類之間的關系。
```java
public class Mother {
@OneToMany(mappedBy = "mother", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Children> childrenList;
}
```
```java
public class Children {
@ManyToOne(targetEntity = Mother.class, cascade = CascadeType.ALL)
@JoinColumn(name = "mother_id", referencedColumnName = "id")
private Mother mother;
}
```
(2)級聯操作。
```java
/************************** Mother -> Children **************************/
/**
* 級聯保存/更新。
* 保存/更新 Mother 的同時,也保存/更新 Children 表。
*/
@Test
public void cascadeSave() {
Mother mother = Mother.builder().name("張母").build();
List<Children> childrenList = new ArrayList<>(1);
Children children01 = Children.builder().name("張三").mother(mother).build();
Children children02 = Children.builder().name("張四").mother(mother).build();
childrenList.add(children01);
childrenList.add(children02);
mother.setChildrenList(childrenList);
Mother mother1 = motherRepository.save(mother);
System.out.println(mother1.getId());
}
/**
* 級聯刪除。
* 刪除 Mother 的同時,也刪除 Children 表。
*/
@Test
public void cascadeDelete() {
Mother mother = Mother.builder().id(2).build();
List<Children> childrenList = new ArrayList<>(1);
Children children01 = Children.builder().id(3).build();
Children children02 = Children.builder().id(4).build();
childrenList.add(children01);
childrenList.add(children02);
mother.setChildrenList(childrenList);
motherRepository.delete(mother);
}
```
```java
/************************** Children -> Mother **************************/
/**
* 級聯保存/更新。
* 保存/更新 Children 的同時,也保存/更新 Mother 表。
*/
@Test
public void cascadeSave() {
Mother mother = Mother.builder().name("王母").build();
List<Children> childrenList = new ArrayList<>(1);
Children children = Children.builder().name("王三").mother(mother).build();
childrenList.add(children);
mother.setChildrenList(childrenList);
Children children1 = childrenRepository.save(children);
System.out.println(children1.getId());
}
```
- MapStruct屬性映射
- MapStruct是什么
- maven依賴
- 基本映射
- 字段名不一致的映射
- 字段類型不一致的映射
- 基本數據類型轉換
- 日期格式轉換
- 使用表達式轉換
- 枚舉映射
- 多個源類的映射
- 集合的映射
- 添加自定義映射方法
- 映射前后
- 添加默認值
- 映射異常處理
- SpringDataJPA
- SpringDataJPA是什么
- 與JPA、Hibernate的關系
- 環境搭建
- 簡單CURD操作
- 內部原理
- 主鍵生成策略
- 聯合主鍵
- 查詢方式
- 方法命名規則查詢
- 限制查詢結果查詢
- 注解@Query查詢
- 命名參數查詢
- SpEL表達式查詢
- 原生查詢
- 更新與刪除
- Specification動態查詢
- 核心接口
- 查詢例子
- 分頁查詢與排序
- 多表查詢
- 一對一查詢
- 一對多查詢
- 多對多查詢
- 注意事項
- Specification多表查詢
- @Query多表查詢
- 只查詢指定字段
- 級聯操作
- 加載規則