Hibernate handle long 0 value instead of NULL in M

2019-06-20 17:55发布

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?

3条回答
女痞
2楼-- · 2019-06-20 18:03

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.

查看更多
不美不萌又怎样
3楼-- · 2019-06-20 18:04
叛逆
4楼-- · 2019-06-20 18:08

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.

查看更多
登录 后发表回答