我想实现软删除,但仍然能够永久删除。有什么方法可以忽略声明的@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...
}
答案 0 :(得分:0)
我在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
实体,则需要先在flush
上调用clear
和EntityManager
方法执行DELETE语句。这样可以确保在删除记录之前,所有待处理的更改都已写入数据库。