Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional in entity field [duplicate]

Can I use Optional in fields of hibernate entity? Maybe with some custom user type?

I know I can use it in methods using AccesType.FIELD (I use AccesType.FIELD anyway).

Why I want this? Well, I want to stay as far away from nulls as possible.

like image 881
korda Avatar asked Mar 23 '16 09:03

korda


1 Answers

You should not use Optional as a field in a class (either for Hibernate use or not).

As stated by the Javadoc, it is a value-based class, so not serializable, and use of reference equality (==) and identity hashcode has unpredictable results.

Instead, you can store an instance of the target class (null is ok in relational databases), and return an Optional from accessors (not the getter, which Hibernates expect to return the same class as the field, if I remember well).

Hope this will help.

like image 68
cdelmas Avatar answered Nov 14 '22 03:11

cdelmas