多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**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()); } ```