子表的Hibernate软删除

时间:2016-10-26 06:14:17

标签: java hibernate one-to-many soft-delete

假设我们有两个实体Customer和AppUser,它们是One-To-Many关系。

客户实体:

@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,然后我saveOrUpdate Customer实体,例如:

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

假设现在我们有四个appUsers,然后

appUsers.remove(oneItem)

saveCustomer(customer);

现在,已删除的appUser已从数据库中删除,并保留三条记录。我仍然想用软删除来处理这种情况,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

最后,我找到了答案,为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;
}

Hibernate doc链接: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-filters