Skip to content

Instantly share code, notes, and snippets.

@rafaeltuelho
Created November 2, 2014 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaeltuelho/167ae7dbc2c747e6e2a1 to your computer and use it in GitHub Desktop.
Save rafaeltuelho/167ae7dbc2c747e6e2a1 to your computer and use it in GitHub Desktop.
Some JPA Query API code snippet samples
public void findindAllUsingJpqlQuery() throws Exception {
// given
String fetchingAllInJpql = "select e from " + ENTITY_NAME
+ " e order by e.id";
// when
System.out.println("Selecting (using JPQL)...");
List<Entity> entities = em.createQuery(fetchingAllInJpql,
Entity.class).getResultList();
// then
System.out.println("Found " + entities.size()
+ " entities (using JPQL):");
}
public void findAllUsingCriteriaApi() throws Exception {
// given
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Entity> criteria = builder
.createQuery(Entity.class);
Root<Entity> entity = criteria.from(Entity.class);
criteria.select(entity);
// TIP: If you don't want to use the JPA 2 Metamodel,
// you can change the get() method call to get("id")
criteria.orderBy(builder.asc(entity.get(Entity_.id)));
// No WHERE clause, which implies select all
// when
System.out.println("Selecting (using Criteria)...");
List<Entity> entities = em.createQuery(criteria).getResultList();
// then
System.out.println("Found " + entities.size()
+ " entities (using Criteria):");
}
public void findUsingCriteriaApiWhere() throws Exception{
// given
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Entity> criteria = builder
.createQuery(Entity.class);
Root<Entity> entity = criteria.from(Entity.class);
criteria.where(builder.equal(entity.get(Entity_.id), id));
Entity entity = em.createQuery(criteria).getSingleResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment