Hibernate handles a long value of 0 instead of NULL in ManyToOne relationships

I use Hibernate to access an obsolete database. For some tables, parent-child reference integrity is not applied, and a long 0 value is used instead of NULL for some "parent" columns in child tables to indicate "no parent".

I still want to use this relationship in the @ManyToOne and @OneToMany , but I get an EntityNotFound error because the value 0 does not match any record in the main table.

What are my options?

+6
source share
3 answers
+8
source

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

@Formula @Formula , as indicated in the documentation , you can use join conditions .

Since I do not know that your data model providing a valid example is complex. Try:

 id_fk is not null or id_fk <> 0 

block.

If this does not fit your needs, you can write your own request loader

If you are using some kind of log, enable the show_sql property. And add org.hibernate.sql DEBUG to your configuration.

0
source

Instead of @JoinColumn, you can use @JoinFormula. Like this

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

The expression means that we are checking the column, and if it is 0 returns NULL. Then hibernate does not look for the related entity.

0
source

Source: https://habr.com/ru/post/900945/


All Articles