在hibernate的常见位置进行逻辑删除

我在我的应用程序中使用Spring和Hibernate。

我只允许在我的应用程序中进行逻辑删除,我需要设置字段isActive = false。 我没有在所有实体中重复相同的字段,而是使用属性和’isActive’的getter-setter创建了一个Base Class。

因此,在删除期间,我调用update()方法并将isActive设置为false。

我无法让这个工作。 如果有任何想法,请告诉我。

基本实体

public abstract class BaseEntity implements IEntity { @Basic @Column(name = "IsActive") protected boolean isActive; public Boolean getIsActive() { return isActive; } public void setIsActive(Boolean isActive) { isActive= isActive; } } 

儿童实体

 @Entity(name="Role") @Table(schema = "dbo") public class MyEntity extends BaseEntity { //remaining entities } 

Hibernate Util类

 public void remove(TEntity entity) { //Note: Enterprise data should be never removed. entity.setIsActive(false); sessionFactory.getCurrentSession().update(entity); } 

尝试将setIsActive方法中的代码替换为:

 public void setIsActive(Boolean isActive) { this.isActive = isActive; } 

在你的代码中使用变量名称而不是this可能是ambiguos …

我认为你还应该在你的抽象类中添加@MappedSuperclass注释来实现字段inheritance。

建议的解决方案(在您对该答案的评论中提到的)的问题是不处理级联删除。

另一种(Hibernate特定的,非JPA)解决方案可能是使用Hibernate的@SQLDelete注释:

http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/querysql.html#querysql-cud

我似乎记得,这个Annotation不能在Superclass上定义,必须在每个Entity类上定义。

但是,逻辑删除的一般问题是,您必须记住过滤每个查询和每个集合映射以排除这些记录。

在我看来,更好的解决方案是完全忘记逻辑删除。 使用Hibernate Envers作为审计机制。 然后,您可以根据需要恢复任何已删除的记录

http://envers.jboss.org/

您可以使用SQLDelete注释…

@ org.hibernate.annotations.SQLDelete;

 //Package name... //Imports... @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 char deleted; 

资料来源: http : //featurenotbug.com/2009/07/soft-deletes-using-hibernate-annotations/