Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate handle long 0 value instead of NULL in ManyToOne relations

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?

like image 723
Vladimir Avatar asked Nov 07 '11 15:11

Vladimir


2 Answers

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

like image 174
JB Nizet Avatar answered Oct 15 '22 22:10

JB Nizet


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.

like image 29
StanislavL Avatar answered Oct 15 '22 21:10

StanislavL