Categories: Java, JPA

How to load nested JPA entities in a single query

jpa-fetch-joinsHave you ever realized that many times when accessing a managed entity’s attribute it’s common to see JPA performing many subsequent queries in the database in order to lazy load information? Well, it’s a good default behavior and works in the majority of the cases but still sometimes we need to modify this behavior on an ad hoc basis or per use case scenario. For these specific situations we can use a handy feature from JPA known as Fetch Joins. In a very abstract way we can say that the Fetch Joins allow us to dynamically define which relations we want to eagerly load when making a query. In this article we are going to retrieve nested JPA entities in a single query avoiding many database calls.

Example

Let’s consider the following example:

Our system has two entities: Customer and Address. The relationship between them is a bidirectional one-to-many from Customer to Address, which means that a Customer can have none or multiple instances of Address. 


Categories: Java, JPA

Persisting enums using JPA attribute converter

persisting enums using jpa attribute converterBefore the JPA 2.1 specification be released in 2013 the simple task to persist and load enums could be performed but not in a simple and decent way. In this article I’m going to present you some old techniques to solve this problem and how the new JPA specification established an appropriate way for persisting enums using JPA attribute converter.

To access the complete JSR 338: Java Persistent 2.1 specification, please follow this link: https://jcp.org/en/jsr/detail?id=338.

Back in the old days (before the JPA 2.1)

The Enumerated techinique

One of the most spreaded solutions for the enums’ persistence problem was the Enumerated technique. It consists in the usage of the Enumerated annotation with EnumType.ORDINAL or EnumType.STRING. I personally don’t like this approach because when we use the EnumType.ORDINAL it assumes the position of the items will never change inside the enum and when using EnumType.STRING we will persist the same string repeated times in the DB.