亲宝软件园·资讯

展开

cascade级联

过期可乐 人气:0

属性

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

加载全部内容

相关教程
猜你喜欢
用户评论