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.
Get this Hibernate Tip as a printable PDF!Join the free Thoughts on Java Library to get access to lots of member-only content, like a printable PDF for this post, lots of cheat sheets and 2 ebooks about Hibernate.
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.