Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
How can I map an optional to-one association to a Java 8 Optional?
Hibernate doesn’t support Optional as an attribute type. But if Hibernate uses field access, you can implement your own getter methods. This provides you the option to wrap the attribute which represents the to-one association into an Optional. You can see an example of it in the following code snippet.
As you can see in the code snippet, I only changed the getPublisher() method. It now uses the ofNullable method to wrap the publisher attribute into an Optional and returns it to the caller.
You can learn more about Hibernate’s Java 8 support in my free ebook: Java 8 support in Hibernate 5.
Hibernate Tips Book
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching and statically and dynamically defined queries.
Get it now as a paperback, ebook or PDF.