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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With