Hibernate 在 ManyToOne 关系中处理长 0 值而不是 NULL

发布于 2024-12-13 20:50:28 字数 249 浏览 4 评论 0原文

我使用 Hibernate 来访问旧数据库。对于某些表,不强制执行父子引用完整性,并且对于子表中的某些“父”列,使用 long 0 值而不是 NULL 来表示“无父”。

我仍然想在 @ManyToOne@OneToMany 字段中使用这些关系,但收到 EntityNotFound 错误,因为 0 值不对应于任何记录在主表中。

我有什么选择?

I use Hibernate to access to a legacy DB. For some tables the parent-child reference integrity is not enforced, and the long 0 value is used instead of NULL for some "parent" columns in child tables to denote "no parent".

I still want to use these relations in @ManyToOne and @OneToMany fields, but get EntityNotFound error since the 0 value does not correspond to any record in master table.

What are my options?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

dawn曙光 2024-12-20 20:50:29

可以使用 @JoinFormula 代替 @JoinColumn。像这样的

@JoinFormula(value="CASE the0isNullColumn"
             + " WHEN 0"
             + " THEN NULL"
             + " ELSE the0isNullColumn"
             + " END")

表达式意味着我们检查该列,如果它是 0,则返回 NULL。然后 hibernate 不会搜索相关实体。

Instead of the @JoinColumn could be used @JoinFormula. Like this

@JoinFormula(value="CASE the0isNullColumn"
             + " WHEN 0"
             + " THEN NULL"
             + " ELSE the0isNullColumn"
             + " END")

The expression means we check the column and if it's 0 return NULL. Then hibernate doesn't search for the related entity.

小耗子 2024-12-20 20:50:29

您可以将其映射到java.lang.Long,默认值为null。或者您可以使用 @PostLoad 并在 0 时将其设为 null。您还可以使用 @Formula 并忽略 0

@Formula 如其 文档可用于加入条件

由于我不知道您的数据模型,提供有效的示例很棘手。尝试使用:

id_fk is not null or id_fk <> 0

块。

如果它不适合您的需求,您可以编写自己的 查询加载器

如果您使用某种日志记录,请启用 show_sql 属性。并将 org.hibernate.sql DEBUG 添加到您的配置中。

You can map it to java.lang.Long which default value is null. Or you can use a @PostLoad and null it if 0. You can also use a @Formula and ignore 0.

The @Formula as written in their documentation can be used to join conditions.

Since I don't know your data model providing a valid example is tricky. Try with:

id_fk is not null or id_fk <> 0

block.

If it does not suit your needs you can write you own Query loader

If you are using some sort of logging enable the show_sql property. And add to your config the org.hibernate.sql DEBUG.

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