在某些情况下如何忽略@SQLDelete批注

时间:2018-08-16 12:45:59

标签: java hibernate annotations sql-delete soft-delete

我想实现软删除,但仍然能够永久删除。有什么方法可以忽略声明的@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...

}

1 个答案:

答案 0 :(得分:0)

我在Hibernate Tips之一中对此进行了更详细的说明。这是它的简短版本:

当您在EntityManager上调用remove方法时,Hibernate将执行@SQLDelete操作中定义的SQL语句。

您无法停用@SQLDelete注释。因此,如果您想从数据库中永久删除记录,则不能使用EntityManager的remove方法。您需要使用JPQL,Criterianative查询来执行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上调用clearEntityManager方法执行DELETE语句。这样可以确保在删除记录之前,所有待处理的更改都已写入数据库。