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:
@Entity
@AutoProperty
public class SomeItem {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    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");

JPA.INSTANCE.save(A);
JPA.INSTANCE.save(B);
JPA.INSTANCE.save(C);

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

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

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

// Printing results
for ( SomeItem si : results ) {
    System.out.println(si);
}
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