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.
Don’t want to read? Watch it here
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.
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.
[show_to accesslevel=”free”]You can learn more about Hibernate’s Java 8 support in my free ebook: Java 8 support in Hibernate 5.[/show_to][hide_from accesslevel=”free”]You can learn more about Hibernate’s Java 8 support in my free ebook: Java 8 support in Hibernate 5.[/hide_from]
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.