7

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.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
korda
  • 804
  • 7
  • 18

1 Answers1

1

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.

cdelmas
  • 840
  • 8
  • 15
  • What is unpredictable about Optional's equals and hashCode implementations? They seem to have a clear, firm contract in the Javadoc to which you link. – Sam Lindsay-Levine Mar 23 '16 at 19:49
  • Sorry for the shortcut. I didn't mean equals and hashcode, but == and identity hashcode. Thank you for the correction. – cdelmas Mar 24 '16 at 12:51