Jakarta EE Components

Data Access with JPA

Composable, type-safe Criteria queries, and Data Access Objects built by delegation, without DAO boilerplate.

There are many ways to implement the Data Access Object pattern in Java. Most of them require you to implement an interface, rely on bytecode generation, or inherit from a base class. Flow Logix takes a different approach: JPAFinder provides the queries, and your DAO delegates to it. How much "magic" you use is up to you.

Create a DAO

The recommended approach is Lombok’s @Delegate annotation. It needs the least code and the least magic, with almost no boilerplate. You can also write forwarding methods by hand, or delegate to JPAFinder from an interface with dynamic proxies or another bytecode generator.

Inject JPAFinder

JPAFinder can be injected with @Inject, and finds the EntityManager through CDI. It is serializable, so it can be used inside @ViewScoped beans, for example.

A simple injected DAO
@Stateless
public class InjectedDAO {
    @Inject
    @Delegate
    JPAFinder<UserEntity> jpaFinder;
}

Create a DAO without injection

DaoHelper can be created with a fluent builder, which needs an EntityManager Supplier and the entity Class:

A simple DAO without injection
@Stateless
public class ExampleDAO {
    @PersistenceContext(unitName = "demo-pu")
    EntityManager em;
    @Delegate
    JPAFinder<UserEntity> jpaFinder = new DaoHelper<>(() -> em, UserEntity.class);
}

Why a Supplier instead of an EntityManager?

The EntityManager is not yet initialized when the DAO object is created. A Supplier delays initializing DaoHelper until the EntityManager is actually needed at run time.

Use a non-default EntityManager

If the default CDI producer for the EntityManager isn’t the right one, use @EntityManagerSelector to specify qualifiers for another producer. First, declare a qualifier:

A qualifier annotation
@Qualifier
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface NonDefault {
}

Then produce the EntityManager with that qualifier:

A non-default EntityManager producer
@Alternative
@RequestScoped
@Priority(APPLICATION + 1)
public class EntityManagerProducer {
    @Getter(onMethod_ = {@Produces, @NotDefault})
    @PersistenceContext(unitName = "nonDefault")
    EntityManager entityManager;
}
Note
Remove the @NonDefault annotation to use it as the default producer. If there is only one persistence unit, unitName can also be omitted.

Now you can inject the EntityManager and DAOs that use it:

Inject a non-default EntityManager
@Stateless
public class InjectedEntityManager {
    @Inject
    @NonDefault
    EntityManager entityManager;
}
An injected DAO with a non-default EntityManager
@Stateless
public class InjectedNonDefaultDAO {
    @Inject
    @Delegate
    @EntityManagerSelector(NonDefault.class)
    JPAFinder<UserEntity> jpaFinder;
}

If @RequestScoped is not available, a stateless EJB producer works well, and may perform better thanks to EJB bean pooling:

A stateless EJB EntityManager producer
@Stateless
@Alternative
@Priority(APPLICATION + 1)
@TransactionAttribute(SUPPORTS)
public class StatelessEntityManagerProducer {
    @Getter(onMethod_ = {@Produces, @NonDefault})
    @PersistenceContext(unitName = "nonDefault")
    EntityManager entityManager;
}

Where is find()?

find() and its related methods are already part of the EntityManager, so JPAFinder doesn’t repeat them. The example below forwards the EntityManager methods, so they are available directly on the DAO. For more find()-style functionality, Jakarta Data or Apache DeltaSpike are a good addition to your architecture.

A DAO that also forwards EntityManager methods
@Stateless
public class ExampleDelegateDAO {
    @Inject
    @Delegate(excludes = EntityManagerExclusions.class)
    EntityManager entityManager;
    @Inject
    @Delegate
    JPAFinderHelper<UserEntity> jpaFinder;
}

Inherit from InheritableDaoHelper

If none of the approaches above work for you, your DAO can inherit from InheritableDaoHelper. This isn’t recommended. Initialize the protected jpaFinder field in a @PostConstruct method, not in the constructor, because the EntityManager is not available yet when the object is created.

An inherited DAO
@Stateless
public class InheritedDAO extends InheritableDaoHelper<UserEntity> {
    @Inject
    EntityManager entityManager;

    @PostConstruct
    void init() {
        jpaFinder = new DaoHelper<>(() -> entityManager, UserEntity.class);
    }
}

Enhance queries

findAll(), findRange() and count() take an optional QueryEnhancement, which adds JPA clauses and hints to the query. QueryEnhancement extends BiConsumer and has several accept convenience methods that can be passed as method references, so enhancements can be composed together.

Enhanced queries with hints
public record CountAndList(long count, List<UserEntity> list) { }
public CountAndList countAndList(String userName) {
    // add "where fullName = 'userName'" clause
    QueryEnhancement<UserEntity> enhancement = (partial, criteria) -> criteria
            .where(partial.builder().equal(partial.root()
                    .get(UserEntity_.fullName), userName));

    return new CountAndList(jpaFinder.count(enhancement::accept),
            jpaFinder.findAll(enhancement::accept)
            .setHint(QueryHints.BATCH_TYPE, BatchFetchType.IN)
            .getResultList());
}
A composable query with its own parameters
public CountAndList extractedCountAndList(String userName) {
    // add "where fullName = 'userName'" clause
    QueryEnhancement<UserEntity> enhancement = (partial, criteria) -> criteria
            .where(partial.builder().equal(partial.root()
                    .get(UserEntity_.fullName), userName));
    // descending order for queries
    QueryEnhancement<UserEntity> orderBy = (partial, criteria) -> criteria
            .orderBy(partial.builder().desc(partial.root().get(UserEntity_.fullName)));

    return new CountAndList(jpaFinder.count(enhancement::accept),
            jpaFinder.findAll(enhancement.andThen(orderBy)::accept)
            .getResultList());
}

Compose filters

Calling where() in more than one QueryEnhancement replaces the earlier restriction, so only the last filter applies. Filters created with QueryEnhancement.filter() are combined with AND instead. Independent filters can be composed with andThen(), in any order, and passed to findAll(), findRange() and count(). JPALazyDataModel applies its filters the same way.

Composable filters
public CountAndList filteredCountAndList(String fullNamePattern, int zipCode) {
    // add "where fullName like 'fullNamePattern'" clause
    QueryEnhancement<UserEntity> byName = QueryEnhancement.filter((cb, user) ->
            cb.like(user.get(UserEntity_.fullName), fullNamePattern));
    // add "and zipCode = 'zipCode'" clause, combined with any other filters
    QueryEnhancement<UserEntity> byZipCode = QueryEnhancement.filter((cb, user) ->
            cb.equal(user.get(UserEntity_.zipCode), zipCode));

    var filters = byName.andThen(byZipCode);
    return new CountAndList(jpaFinder.count(filters::accept),
            jpaFinder.findAll(filters::accept).getResultList());
}

Add restrictions to an existing query

QueryEnhancement.filter() creates a reusable filter that can be shared between find and count queries and composed with andThen(). CriteriaExtensions.restrict(query, restriction) is the operation underneath it: it adds a restriction, in place, to a CriteriaQuery you already have, with or without a finder. With Lombok’s @ExtensionMethod(CriteriaExtensions.class) on the class, it is called as if CriteriaQuery declared it, as an additive alternative to where().

Additive restrictions
public List<UserEntity> filteredList(String fullNamePattern, int zipCode) {
    return jpaFinder.findAll(qc -> qc.query()
                    // "where fullName like 'fullNamePattern' and zipCode = 'zipCode'"
                    .restrict(qc.builder().like(qc.root().get(UserEntity_.fullName), fullNamePattern))
                    .restrict(qc.builder().equal(qc.root().get(UserEntity_.zipCode), zipCode)))
            .getResultList();
}

Build criteria queries from a function

createQuery(criteria) creates a query that selects the entity, and passes the CriteriaQuery and its Root to a function that adds restrictions and ordering. The function is a plain BiConsumer, usually written in place as a lambda. To share one function between find and count queries, use a QueryEnhancement as shown above.

A criteria query from a function
public List<UserEntity> findPage(String userName, int first, int pageSize) {
    // "where fullName = 'userName' order by userId desc"
    return jpaFinder.createQuery((query, user) -> query
                    .where(user.get(UserEntity_.fullName).equalTo(userName))
                    .orderBy(jpaFinder.getEntityManager().get().getCriteriaBuilder()
                            .desc(user.get(UserEntity_.userId))))
            .setFirstResult(first).setMaxResults(pageSize)
            .getResultList();
}

Criteria API extension methods

CriteriaExtensions has the same operations as static methods that don’t need a finder. createQuery(builder, entityClass, criteria) implements the API proposed for Jakarta Persistence, CriteriaBuilder.createQuery(Class, BiConsumer), and executeIn(query, entityManager) creates the TypedQuery. With Lombok’s @ExtensionMethod(CriteriaExtensions.class) on the class, they are called as if CriteriaBuilder and CriteriaQuery declared them.

Extension methods
public List<UserEntity> findByName(String userName) {
    var em = jpaFinder.getEntityManager().get();
    return em.getCriteriaBuilder().createQuery(UserEntity.class, (query, user) -> query
                    .where(user.get(UserEntity_.fullName).equalTo(userName)))
            .executeIn(em)
            .getResultList();
}

Type-safe native queries

JPANativeQuery has a convenience method, createNativeQuery(), that returns a TypedNativeQuery. It is a thin wrapper over JPA’s Query, but its getResult*() methods return typed results through generics, so there is no casting and the results are easier and safer to use.

A native query
public List<UserEntity> findByNative(String sql) {
    return jpaFinder.createNativeQuery(sql, jpaFinder.getEntityClass()).getResultList();
}