Tuesday, 11 September 2012

Select From JPA Criteria API Example

This post describes how to generate Select From queries using the JPA Criteria API. All code examples are available from Github in the JPA directory. Some error messages will be displayed when running some examples because of a known and harmless issue.

This code example relies on a simple item:
public class SomeItem {

    private long Id;

    private String data;

    // Constructors, Setters & Getters, Pojomatic...

The following code creates and executes a simple Select From query using the JPA Criteria API:
// Creating some data
SomeItem A = new SomeItem("rttt");
SomeItem B = new SomeItem("qqqq");
SomeItem C = new SomeItem("zzzz");


CriteriaBuilder cb = JPA.INSTANCE.EM.getCriteriaBuilder();

// Constructing Select * from SomeItem
CriteriaQuery<SomeItem> q = cb.createQuery(SomeItem.class);
Root<SomeItem> c = q.from(SomeItem.class);

// Executing the query
TypedQuery<SomeItem> query = JPA.INSTANCE.EM.createQuery(q);
List<SomeItem> results = query.getResultList();

// Printing results
for ( SomeItem si : results ) {
The generated output is:
SomeItem{Id: {1}, data: {rttt}}
SomeItem{Id: {2}, data: {qqqq}}
SomeItem{Id: {3}, data: {zzzz}}
More about query parameters here.

No comments:

Post a comment