Hibernate:如何仅获取未逻辑删除的对象

发布于 2024-09-28 17:53:12 字数 940 浏览 8 评论 0原文

我们数据库中的几乎每个表都有一个审计表的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱ヾ落雨殇 2024-10-05 17:53:12

IMO,实现软删除的最简单方法是在实体中添加一个标志并使用:

  • @SQLDelete 注释来覆盖默认的 Hibernate delete (并执行标志的更新)
  • @Where (或 @Filters?)对实体和关联进行注释以过滤已删除的实体,

但不确定这如何适合您的 Auditing 表。还需要一些进一步的探索和测试。

资源

IMO, the easiest way to implement a soft-delete would be to add a flag in your entities and to use:

  • the @SQLDelete annotation to override the default Hibernate delete (and perform an update of the flag)
  • the @Where (or @Filters?) annotation on your entities and associations to filter the deleted entities

Not sure how this can fit with your Auditing table though. Some further exploration and testing are required.

Resources

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文