Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate ORM - supporting Java 1.8 Optional for entity properties

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!

like image 483
Federico Gaule Palombarani Avatar asked Jul 26 '14 21:07

Federico Gaule Palombarani


People also ask

What is optional in Hibernate?

Java 8 introduced Optional<T> as a container object which may contain null values. It's often used to indicate to a caller that a value might be null and that it need to be handled to avoid NullPointerExceptions.

What is the difference between Hibernate and ORM?

Hibernate is an object-relational mapping solution for Java environments. Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables.

Is Hibernate ORM good?

JPA and Hibernate ORM are a great fit for standard CRUD operations. They make the implementation of these use cases very easy and efficient.

What is Hibernate ORM used for?

Hibernate ORM enables developers to more easily write applications whose data outlives the application process. As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data persistence as it applies to relational databases (via JDBC).


1 Answers

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);
}
like image 175
Vlad Mihalcea Avatar answered Oct 13 '22 02:10

Vlad Mihalcea