属性
-
-
CascadeType.REMOVE
:级联删除,当调用remove()方法删除Order实体时会先级联删除OrderItem的相关数据 -
CascadeType.MERGE
:级联更新,当调用了Merge()方法,如果Order中的数据改变了会相应的更新OrderItem中的数据 -
CascadeType.PERSIST
:级联保存,当调用了Persist() 方法,会级联保存相应的数据 -
CascadeType.DETACH
:级联脱管/游离操作,如果你要删除一个实体,但是它有外键无法删除,你就需要这个级联权限了。它会撤销所有相关的外键关联。 CascadeType.ALL
:包含以上所有级联属性
级联保存,级联修改,级联删除案例
//学校类 @Table(name = "t_school") @Entity @Getter @Setter public class School extends BaseEntity { private String name; @JsonIgnore @OneToMany(mappedBy = "school", cascade = {CascadeType.REFRESH, CascadeType.REMOVE, CascadeType.PERSIST}, fetch = FetchType.LAZY) private List<Student> students = new ArrayList<>(); //手动构造添加学生的方法 public void addStudent(Student stu){ if(!students.contains(stu)){ stu.setSchool(this); //设置学校 this.students.add(stu); //添加 } } //重写equals和hashCode方法 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; School school = (School) o; return Objects.equals(name, school.name) && Objects.equals(students, school.students); } @Override public int hashCode() { return Objects.hash(name, students); } } //学生类 @Table(name = "t_student") @Entity @Getter @Setter public class Student extends BaseEntity { private String name; private String age; @ManyToOne(cascade = CascadeType.REFRESH,optional = false) @JoinColumn(name = "SCHOOL_ID") private School school; } //测试类 @RunWith(SpringRunner.class) @SpringBootTest public class SchoolDaoTest { @Autowired private SchoolDao schoolDao; @PersistenceContext private EntityManager em; @Test public void testSave() { School school = new School(); school.setName("学校1"); Student student1 = new Student(); student1.setAge("18"); student1.setName("张三"); Student student2 = new Student(); student2.setAge("18"); student2.setName("李四"); school.addStudent(student1); school.addStudent(student2); //经过测试,用save方法也是可以的 schoolDao.saveAndFlush(school); //这个方法dao类需要去继承JpaRepository } @Test public void testDel() { schoolDao.deleteById(1365157538168864L); }
/**
* 级联更新
*/
@Test
public void testMerge(){
Optional<School> rs = schoolDao.findById(1365164498616352L);
School school = rs.isPresent()? rs.get() : null;
if(school != null){
school.setName("学校2");
List<Student> students = school.getStudents();
if(students != null && students.size() > 0){
for (Student student : students) {
student.setName("改名字");
}
}
school.setStudents(students);
schoolDao.save(school);
}
}
}
经过测试,在保存school的时候会一起把student一起保存,级联保存 删除学校会把级联的student一起删除
级联更新 `cascade`属性加上`CascadeType.MERGE`,注意:不能和懒加载一起使用,正确加载方式:fetch = FetchType.EAGER