When I wrote my examples on how to use JavaFX and JPA 2.0 (part II and III), I made some other tries using Criteria API. Example using like and a JPA parameter
String param = "Arc%";
Query query = em.createQuery(
"select m from Music m where m.artisteName like :param");
query.setParameter("param", param);
List<Music> musics = query.getResultList();
for (Music music : musics){
System.out.println(music);
}
Equivalent with Criteria API |
String param = "Arc%";
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Music> query = cb.createQuery(Music.class);
Root<Music> music3 = query.from(Music.class);
query.where(cb.like(music3.<String>get("artisteName"),
cb.parameter(String.class, "param")));
TypedQuery<Music> tq = em.createQuery(query);
tq.setParameter("param", param);
List<Music> musics = tq.getResultList();
for (Music music : musics){
System.out.println(music);
}
Example of criteria API using count
String param = "Archive";
Query query = em.createQuery(
"select count(m) from Music m where m.artisteName = :artisteNameParam");
query.setParameter("artisteNameParam", param);
Long count1 = (Long)query.getSingleResult();
System.out.println("count : "+count1);
Equivalent with Criteria API |
String param = "Archive";
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> query = cb.createQuery(Long.class);
Root<Music> music = query.from(Music.class);
query.select(cb.count(music));
query.where(cb.equal(music.<String>get("artisteName"),
cb.parameter(String.class,"artisteNameParam")));
TypedQuery<Long> tq = em.createQuery(query);
tq.setParameter("artisteNameParam", param);
Long count = tq.getSingleResult();
System.out.println("count : "+count);
Example of criteria using distinct
String param = "Arc%";
Query query = em.createQuery(
"select distinct m.artisteName from Music m where m.artisteName like :param");
query.setParameter("param", param);
List<String> artistes= query.getResultList();
for (String artiste : artistes){
System.out.println(artiste);
}
Equivalent with Criteria API |
String param = "Arc%";
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> query = cb.createQuery(String.class);
Root<Music> music = query.from(Music.class);
query.select(music.<String>get("artisteName"));
query.distinct(true);
query.where(cb.like(music.<String>get("artisteName"),
cb.parameter(String.class, "param")));
TypedQuery<String> tq = em.createQuery(query);
tq.setParameter("param", param);
List<String> artistes = tq.getResultList();
for (String artiste : artistes){
System.out.println(artiste);
}
Aucun commentaire:
Enregistrer un commentaire