[hibernate-dev] 5.2 Java 8 Optional support

Steve Ebersole steve at hibernate.org
Wed May 4 15:30:37 EDT 2016


Since 5.2 is moving to baseline on Java 8 we've been looking at Java 8
features we might leverage in Hibernate and allow users to leverage.

The first one I am tackling is "support for Optional", which will have the
following parts:

   1. Support models which define attributes using Optional
   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
   Optional
   - 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).


More information about the hibernate-dev mailing list