1. Support models which define attributes using Optional
1. JPA 2.1 Spec. §2.1 The Entity Class:
If an entity instance is to be passed by value as a detached
object (e.g., through a remote interface), the entity class must
implement the Serializable interface.
Optional is not Serializable. Therefore when you use detached
entities in your application, then you cannot use Optional as
2. Using Optional as field type is considered a misuse of the API.
See the comment from Stuart Marks:
IntelliJ IDEA warns you for example when you use Optional
as field type.
2. Allow retrieving Objects from Hibernate as Optional
The second part is really about allowing users to request that Hibernate
return Optional in cases where the result may be null. This will be very
targeted to cases where the user ask Hibernate to get an entity, e.g.
Session#get, Session#find, *LoadAccess#load, Query#getSingleResult,
Query#uniqueResult, etc. I am against adding any more overloaded
Session#get methods, so I will actually limit that to *LoadAccess#load. So
here I propose adding:
1. Optional<R> *LoadAccess<R>#loadOptional()
2. Optional<R> Query<R>#uniqueResultOptional()
The second part is about accepting Optionals from the user. The biggest
use case here is the use of Optional in the application domain model for
persistent attributes. Again tis breaks down into 2 concerns:
1. Getting/setting values of such persistent attributes.
2. Appropriately marking column(s) of such persistent attributes
nullable (by default, at least)
The first concern initially seems like a god candidate for Types, but it
really does not fit. I think the better place to deal with this is
PropertyAcess and specifically the Getter and Setter it returns. The
logical there being that the "type" is still the <T>, not the Optional.
Handling column nullability will be a challenge given the current state of
annotation binding code.
Another consideration is accepting Query parameters that are Optional. It
is a silly idea to pass an Optional as a parameter, I agree. But there are
places it legitimately comes up:
- setParameter( ..., a.getSomeOptional() ) - where getSomeOptional is an
- setProperties( a ) - where a is a bean that defines Optional(s)
Anyway, that's the plan and I'm sticking to it (unless I hear feedback).
hibernate-dev mailing list