Introduction

Java 1.8 introduced the java.util.Optional container object that may or may not contain a certain value. Combining Optional and streams is very handy. Therefore, you might want that some nullable entity attributes be exposed as Optional.

This article is going to demonstrate what are caveats of using Optional with entity attributes, and how you can overcome them.

Domain Model

Let’s assume we have the following entity model:

The Post entity is the root in our entity aggregate. There can be multiple PostComment(s) associated with a Post, and each PostComment can have an Attachment. Because the Attachment is not mandatory, it makes sense to use an Optional container for it.

Optional and Serializable

The java.util.Optional does not implement the Serializable interface. For this reason, we should never map an entity attribute as Optional because that will restrict the entity usage.

For instance, we could have a detached instance stored in the HttpSession because we are operating a long conversation workflow. Every object stored in the HttpSession should be Serializable because the session may be clustered on several web nodes.

For all these reasons, an entity attribute should not be mapped as a java.util.Optional.

All is not lost

But just because we cannot map an entity attribute as Optional, it does not mean we cannot expose it using an Optional container. If we are using field-based access persistence, then the underlying entity attribute can be mapped using the actual persisted type, while the getter method can use an Optional instead.