Social Media

JPA Criteria API

Ive got to say I don’t like the JPA Criteria API – some love it, but I much prefer JPQL. Consider the following JPQL –

SELECT ag FROM agreement ag

This would be expressed in the Criteria API by –

[sourcecode lang=”java”] CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Agreement> cq = cb.createQuery(Agreement.class); // Table
Root<Agreement> agreement = cq.from(Agreement.class); // FROM Agreement ag
cq.select(agreement); // SELECT ag
TypedQuery<Agreement> q = em.createQuery(cq); // Note the preference of TypedQuery
List<Agreements> allAgreements = q.getResultList();
[/sourcecode]

But the choice isn’t purely preference, and the Criteria API has its place when it comes to stricter Type safety. The reason for this is that the Criteria API is backed by a data metamodel of the underlying tables, so less room for the developer to muck things up by passing a letter into a field expecting a number.

[sourcecode lang=”java”] @Entity
class Agreement {
private Long id;
private String agreementName;
private Integer agreementYear;
private List claims;
private User createdBy;
}

// JPA generates a metamodel –

@Static Metamodel(Agreement.class)
public class Agreement _ {
public static volatile SingularAttribute<Agreement , Long> id;
public static volatile SingularAttribute<Agreement , String> agreementName;
public static volatile SingularAttribute<Agreement , Integer > agreementYear;
public static volatile ListAttribute<Agreement, Claims> claims;
public static volatile SingularAttribute<Agreement, User> createdBy;
}

// Example Query
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Agreement.class);
Root<Pet> pet = cq.from(Agreement.class);
EntityType<Agreement> Agreement_ = agreement.getModel();
[/sourcecode]

You can also access the metamodel directly

[sourcecode lang=”java”] Metamodel m = em.getMetamodel();
EntityType<Agreement> Agreement_ = m.entity(Agreement.class);
[/sourcecode]

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: