21

I'm trying to use java.util.Optional 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);
   }
}

Thanks!

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • See [Item 15: Do Not Use Optional in Setters Arguments](https://dzone.com/articles/using-optional-correctly-is-not-optional) – Navigatron Jan 22 '21 at 14:26

1 Answers1

40

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);
}
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • 1
    i saw this and i really have to say, that you never ever should use Optional in attributes only as return value of methods. – dom Sep 14 '17 at 15:25
  • 7
    i saw this and i really have to say, that you can use optional whenever you want to avoid `null` in your codebase as long as you feel comfortable with it and even if everyone keeps repeating language architect who does not want to have "monadic-ish" composition of "optionality" in the core library in favor of insisting to use Hoars 1 billion dollar mistake. Just make sure to safeguard against external libraries/apis" that come around with nullish objects and you will be fine. – dwegener Oct 02 '17 at 16:01