问题描述
如果我有3个相互关联的课程。
In case I have 3 class which are connected each other.
会议室等级
@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。我也希望级联我的删除,所以如果任何房间被删除,那么与该房间相关的每个人和电话也将被删除(删除列值设置为1)。我的问题是如何在 Hibernate
上执行此操作?是否有任何优雅的方法来实现这些东西?
What i want to do here is implement soft delete with inserting value 1 to deleted column for deleted item and inserting value 0 for exist item. Also I want Cascading my deletion, so if any room deleted, then every person and phone which is related with that room will be also deleted("deleted" column value set to 1). My question is how can I do that on Hibernate
? Is there any elegant way to implement this stuff?
推荐答案
使用Hibernate实现软删除的最佳方法是使用@ SQLDelete类的注释。
The best way to achieve a soft delete with Hibernate is to use the @SQLDelete annotation on your classes.
确保你的映射设置为级联删除
make sure your mapping is set to cascade delete
调用session.delete(yourClass)应该能够实现你的软件删除
calling session.delete(yourClass) should achive your soft delete
//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 ")
这篇关于使用更新Cascade进行休眠软删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!