Created
November 2, 2014 21:44
-
-
Save rafaeltuelho/167ae7dbc2c747e6e2a1 to your computer and use it in GitHub Desktop.
Some JPA Query API code snippet samples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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