Hibernate Tips: How to map an association to an Optional

By Thorben Janssen


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.

public class Book implements Serializable {


	private Publisher publisher;


	public Optional getPublisher() {
		return Optional.ofNullable(this.publisher);

	public void setPublisher(final Publisher publisher) {
		this.publisher = publisher;

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.

Learn More:

You can learn more about Hibernate’s Java 8 support in my free ebook: Java 8 support in Hibernate 5.


Hibernate Tips Book

Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.

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!



About the author

Thorben is an independent consultant, international speaker, and trainer specialized in solving Java persistence problems with JPA and Hibernate.
He is also the author of Amazon’s bestselling book Hibernate Tips - More than 70 solutions to common Hibernate problems.

Leave a Reply

Your email address will not be published. Required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}