Hibernate 在 ManyToOne 关系中处理长 0 值而不是 NULL
我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
NotFound
< /a> 注释:参见 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-manytoone
Use the
NotFound
annotation:See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-manytoone
可以使用
@JoinFormula
代替@JoinColumn
。像这样的表达式意味着我们检查该列,如果它是 0,则返回 NULL。然后 hibernate 不会搜索相关实体。
Instead of the
@JoinColumn
could be used@JoinFormula
. Like thisThe expression means we check the column and if it's 0 return NULL. Then hibernate doesn't search for the related entity.
您可以将其映射到
java.lang.Long
,默认值为null。或者您可以使用@PostLoad
并在0
时将其设为 null。您还可以使用@Formula
并忽略0
。@Formula
如其 文档可用于加入条件
。由于我不知道您的数据模型,提供有效的示例很棘手。尝试使用:
块。
如果它不适合您的需求,您可以编写自己的 查询加载器
如果您使用某种日志记录,请启用
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 if0
. You can also use a@Formula
and ignore0
.The
@Formula
as written in their documentation can be used tojoin conditions
.Since I don't know your data model providing a valid example is tricky. Try with:
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 theorg.hibernate.sql
DEBUG
.