Ton*_*ony 2 java hibernate one-to-many soft-delete
假设我们有两个实体Customer和AppUser,它们是一对多关系。
客户实体:
@Entity
@Table(name = "CUSTOMER")
//Override the default Hibernation delete and set the deleted flag rather than deleting the record from the db.
@SQLDelete(sql="UPDATE customer SET deleted = '1' WHERE id = ?")
//Filter added to retrieve only records that have not been soft deleted.
@Where(clause="deleted <> '1'")
public class Customer implements java.io.Serializable {
private long id;
private Billing billing;
private String name;
private String address;
private String zipCode;
private String city;
private String state;
private String notes;
private char enabled;
private char deleted;
private Set appUsers = new HashSet(0);
//Constructors...
//Getters and Setters...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "customer")
//Filter added to retrieve only records that have not been soft deleted.
@Where(clause="deleted <> '1'")
public Set getAppUsers() {
return this.appUsers;
}
public void setAppUsers(Set appUsers) {
this.appUsers = appUsers;
}
}
Run Code Online (Sandbox Code Playgroud)
AppUser实体:
@Entity
@Table(name = "APP_USER")
//Override the default Hibernation delete and set the deleted flag rather than deleting the record from the db.
@SQLDelete(sql="UPDATE app_user SET deleted = '1' WHERE id = ?")
//Filter added to retrieve only records that have not been soft deleted.
@Where(clause="deleted <> '1'")
public class AppUser implements java.io.Serializable {
private long id;
private Customer customer;
private AppRole appRole;
private char enabled;
private String username;
private String appPassword;
private Date expirationDate;
private String firstName;
private String lastName;
private String email;
private String phone;
private String fax;
private char deleted;
private Set
persons = new HashSet(0);
//Constructors...
//Getters and Setters...
}
Run Code Online (Sandbox Code Playgroud)
软删除对他们两个都很好。
我的问题是,当我从客户集中删除一个项目,然后我保存或更新客户实体时,如何软删除AppUser,例如:
Customer customer = getCustomerById(id);
Set<AppUser> appUsers = customer.getAppUsers();
Run Code Online (Sandbox Code Playgroud)
假设现在我们有四个appUsers
appUsers.remove(oneItem)
saveCustomer(customer);
Run Code Online (Sandbox Code Playgroud)
现在,已删除的appUser已从数据库中硬删除,并保留三个记录。我仍然想使用软删除来处理这种情况,有人可以帮忙吗?
最后,我找到了答案,为Customer类的集合添加@SQLDelete。
@SQLDelete(sql="UPDATE customer SET deleted = '1' WHERE id = ?")
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "customer")
//Filter added to retrieve only records that have not been soft deleted.
@Where(clause="deleted <> '1'")
public Set getAppUsers() {
return this.appUsers;
}
Run Code Online (Sandbox Code Playgroud)
Hibernate文档链接:http : //docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-filters
| 归档时间: |
|
| 查看次数: |
3436 次 |
| 最近记录: |