子 table 的休眠软删除

Hibernate soft deletion for child table

假设我们有两个实体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;
    }
}

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...
}

软删除对他们两个都很好。

我的问题是,当我从 Customer 集合中删除一个项目时,如何软删除 AppUser,然后我保存或更新 Customer 实体,例如:

Customer customer = getCustomerById(id);
Set<AppUser> appUsers = customer.getAppUsers();

假设现在我们有四个 appUser,那么

appUsers.remove(oneItem)

saveCustomer(customer);

现在删除的appUser已经从数据库中硬删除了,还剩下3条记录。我仍然想使用软删除来处理这种情况,有人可以帮忙吗?

终于找到答案了,为Customerclass的集合添加@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;
}

休眠文档 link: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-filters