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!
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.
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.
JPA and Hibernate ORM are a great fit for standard CRUD operations. They make the implementation of these use cases very easy and efficient.
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).
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);
}
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