Hibernate handle long 0 value instead of NULL in M

2019-06-20 17:54发布

问题:

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.