cascade級聯關系操作案例詳解
屬性
-
CascadeType.REFRESH
:級聯刷新,當多個用戶同時作操作一個實體,為瞭用戶取到的數據是實時的,在用實體中的數據之前就可以調用一下refresh()方法 -
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
到此這篇關於cascade級聯關系的文章就介紹到這瞭,更多相關cascade級聯關系內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringData JPA中@OneToMany和@ManyToOne的用法詳解
- SpringBoot + JPA @ManyToMany的操作要點說明
- Java Hibernate中的持久化類和實體類關系
- 基於Jpa中ManyToMany和OneToMany的雙向控制
- Java如何重寫object類的equals方法詳解