我想实现软删除,但仍然可以永久删除。有什么办法可以忽略声明的@SQLDelete()注释,或者说:
@SQLDelete("IF expression THEN UPDATE statement ELSE delete statement")
编辑:
这是相关实体。
@Indexed
@Entity
@DynamicUpdate
@FilterDefs({
@FilterDef(name = "tenantFilter", parameters = {@ParamDef(name = "tenantId", type = "string")}),
@FilterDef(name = "deleteFilter")
})
@Filters({
@Filter(name = "tenantFilter", condition = "tenant_id = :tenantId"),
@Filter(name = "deleteFilter", condition = "deleted = false")
})
@SQLDelete(sql ="UPDATE Antwort SET deleted = true, date_modified = NOW() WHERE ID = ?; DELETE FROM Antwort WHERE deleted = true AND kundenentwurf_id IS NOT NULL", check = ResultCheckStyle.NONE)
public class Antwort implements TenantSupport, ISoftDeleteModel{
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String tenantId;
@Column(nullable = false)
private Boolean deleted;
private Date dateModified;
@ManyToOne(fetch = FetchType.LAZY)
private Organisation organisation;
@ManyToOne(fetch = FetchType.LAZY)
private Projekt projekt;
@ManyToOne(fetch = FetchType.LAZY)
private Kundenentwurf kundenentwurf;
private Integer nummer;
private String frage;
private String antwort;
//getters, setters and contructors...
}
最佳答案
我在我的Hibernate Tips之一中对此进行了更详细的解释。这是它的简短版本:
当您在EntityManager
上调用remove方法时,Hibernate将执行@SQLDelete
操作中定义的SQL语句。
您无法停用@SQLDelete
注释。因此,如果您想从数据库中永久删除记录,则不能使用EntityManager
的remove方法。您需要使用JPQL,Criteria或native查询执行SQL DELETE语句。
这是JPQL DELETE语句的示例:
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
// do something ...
// add this if you fetched the Book entity in this session
em.flush();
em.clear();
Query query = em.createQuery("DELETE Book b WHERE id = :id");
query.setParameter("id", 1L);
query.executeUpdate();
em.getTransaction().commit();
em.close();
如果您在当前的Hibernate会话中获取了要删除的
Book
实体,则需要在执行DELETE语句之前调用flush
上的clear
和EntityManager
方法。这样可以确保在删除记录之前,所有未决的更改都已写入数据库。