Hibernate:如何仅获取未逻辑删除的对象
我们数据库中的几乎每个表都有一个审计表的 FK,用于记录创建、更新和删除状态(日期和用户名)。
我们将审核表映射到 Auditing 类并按如下方式使用它:
@MappedSuperclass
public class BusinessObject extends DataObject {
private static final long serialVersionUID = -1147811010395941150L;
@OneToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinColumn(name = "AUD_ID")
private AuditingObject auditing;
...
正如您所期望的,几乎每个实体都从 BusinessObject 扩展。
有没有一种简单的方法可以说,对于每个businessObject,只接收“auditing.deleted is null”。
我尝试在businessObject 中添加@Where 和@WhereJoinTable,但这似乎没有按我的预期工作。
目前,我已经对其中一个查询执行了此操作,并且有效,但我不想对所有查询执行此操作,因为我们有大约 150 个查询。
@NamedQuery(
name="allCountries",
query="SELECT c FROM Country c"
+ " LEFT JOIN FETCH c.labelDefinition "
+ " LEFT JOIN FETCH c.labelDefinition.translations "
+ " WHERE c.auditing.deleted is null"
+ " ORDER BY c.code"
)
Nearly every table in our database has a FK to the Auditing table which logs created, updated and deleted status (date and username).
We mapped the auditing table to the Auditing class and use it like this:
@MappedSuperclass
public class BusinessObject extends DataObject {
private static final long serialVersionUID = -1147811010395941150L;
@OneToOne(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
@JoinColumn(name = "AUD_ID")
private AuditingObject auditing;
...
As you'd expect, nearly every entity extends from BusinessObject.
Is there an easy way of saying, for every businessObject, only receive "auditing.deleted is null".
I've tried adding a @Where and @WhereJoinTable in the businessObject but this doesn't seem to work as I expect.
Currently, i've done this to one of my queries and this works, but I'd hate to do this for all queries since we have about 150.
@NamedQuery(
name="allCountries",
query="SELECT c FROM Country c"
+ " LEFT JOIN FETCH c.labelDefinition "
+ " LEFT JOIN FETCH c.labelDefinition.translations "
+ " WHERE c.auditing.deleted is null"
+ " ORDER BY c.code"
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IMO,实现软删除的最简单方法是在实体中添加一个标志并使用:
@SQLDelete
注释来覆盖默认的 Hibernatedelete
(并执行标志的更新)@Where
(或@Filters
?)对实体和关联进行注释以过滤已删除的实体,但不确定这如何适合您的
Auditing
表。还需要一些进一步的探索和测试。资源
IMO, the easiest way to implement a soft-delete would be to add a flag in your entities and to use:
@SQLDelete
annotation to override the default Hibernatedelete
(and perform an update of the flag)@Where
(or@Filters
?) annotation on your entities and associations to filter the deleted entitiesNot sure how this can fit with your
Auditing
table though. Some further exploration and testing are required.Resources