小编典典

使用更新级联进行hibernate软删除

hibernate

如果我有3个相互连接的类。

room等级

@Entity
@Table(name="table_room")
Class Room{
    @Id
    @GeneratedValue
    @Column(name="id_room")
    private Integer id;

    @Column(name="name")
    private String name;

    @OneToMany(mappedBy="room")
    private List<Person> people;

    @Column(name="deleted")
    private int deleted;
}

person clas

 @Entity
@Table(name="table_person")
Class Person{
    @Id
    @GeneratedValue
    @Column(name="id_person")
    private Integer id;

    @Column(name="name")
    private String name;

    @ManyToOne
    @JoinColumn(name="id_room")
    private Room room;

    @OneToMany(mappedBy="person")
    private List<Phone> phones;

    @Column(name="deleted")
    private int deleted;
}

table_phone

 @Entity
@Table(name="table_phone")
Class Phone{
    @Id
    @GeneratedValue
    @Column(name="id_person")
    private Integer id;

    @Column(name="name")
    private String name;

    @ManyToOne
    @JoinColumn(name="id_person")
    private Person person;

    @Column(name="deleted")
    private int deleted;
}

我要在这里执行的是实现软删除,即在已删除项目的已删除列中插入值1,在现有项目中插入值0。另外,我还希望级联删除操作,因此,如果删除任何会议室,那么与该会议室相关的每个人和电话也将被删除(“已删除”列值设置为1)。我的问题是我该怎么做Hibernate?有什么优雅的方法可以实现这些东西吗?


阅读 408

收藏
2020-06-20

共1个答案

小编典典

使用Hibernate实现软删除的最佳方法是在类上使用@SQLDelete批注。

确保您的映射设置为级联删除

调用session.delete(yourClass)应该可以实现软删除

hibernate文档

//used to overide the normal delete behavior
@SQLDelete(sql="UPDATE (table_name) SET deleted = '1' WHERE id = ?")
//optional Use this to exclude deleted element from get 
@Where(clause="deleted <> '1'")
//OR (Filter may also be used if you need to load deleted items occasionally)
@FilterDef(name="ProductFilter",defaultCondition="deleted <> 1 ")
2020-06-20