如果我有3个相互连接的课程。
房间类
@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;
}
人员类
@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;
}
然后是电话课程
@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。我也希望级联我的删除,所以如果任何房间被删除,那么与该房间相关的每个人和电话也将被删除(&#34;删除&#34;列值设置为1)。我的问题是如何在Hibernate
上执行此操作?是否有任何优雅的方式来实现这些东西?
答案 0 :(得分:1)
使用Hibernate实现软删除的最佳方法是在类上使用@SQLDelete注释。
确保您的映射设置为级联删除
调用session.delete(yourClass)应该实现软删除
//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 ")