Hibernate Tips: How to map an association to an Optional


Take your skills to the next level!

The Persistence Hub is the place to be for every Java developer. It gives you access to all my premium video courses, monthly Java Persistence News, monthly coding problems, and regular expert sessions.


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.

Question:

How can I map an optional to-one association to a Java 8 Optional?

Solution:

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.

@Entity
public class Book implements Serializable {

	…

	@ManyToOne
	@JoinColumn(name=”publisherid”)
	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!

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.