Hibernate handle long 0 value instead of NULL in ManyToOne relations

孤者浪人 提交于 2020-01-03 10:39:09

问题


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?


回答1:


Use the NotFound annotation:

@NotFound(action = NotFoundAction.IGNORE)

See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-manytoone




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8038737/hibernate-handle-long-0-value-instead-of-null-in-manytoone-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!