Federico Gaule Palombarani Federico Gaule Palombarani - 3 months ago 21
Java Question

Hibernate ORM - supporting Java 1.8 Optional for entity properties

I'm trying to use

in some Persistent classes. Is there any workaround to make it work?
I have tried using UserType, but its not possible to handle something like Optional without mapping it to SQL types by hand (not acceptable)
I also tried to use JPA Converter, but it doesn't support Parameterized Types.
I could use wrapping getters and setters like, but it's more like a hack than a solution

public class MyClass {
private MyOtherClass other;

public Optional<MyOtherClass> getOther() {
return Optional.ofNullable(other);

public voud setOther(Optional<MyOtherClass> other) {
this.other = other.orElse(null);



As explained in this blog post, you cannot use the java.util.Optional as a persisted entity attribute since Optional is not Serializable.

However, assuming that you are using field-based access, you can use the Optional container in your getter/setter methods.

Hibernate can then take the actual type from the entity attribute, while the getter and setter can use Optional:

private String name;

public Optional<String> getName() {
    return Optional.ofNullable(name);