How to do JPA query with Criteria Clause? - java

First I want to do a query like
"select count(*) from Post p where p.tag in (tagArray) "
where tagArray is "'tag1','tag2','tag3'".then I'd like to do a paginate query:
query.setFirstResult(int1).setMaxResult(int2);
I don't know how to write this query. I searched the posts ,can't find answers, so can anybody give me any advice? thanks.

Here's sample code:
// get an entity manager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaManager");
EntityManager em = emf.createEntityManager();
// create query
Query query = em.createQuery("select count(*) from Post p where p.tag in (tagArray)") // use parameters here when necessary
.setFirstResult(int1)
.setMaxResults(int2);
// get result
query.getResultList();
Update:
If you want to create query by criteria, try this:
CriteriaBuilder builder = em.getCriteriaBuilder(); // em is as the same the the above
CriteriaQuery<Post> query = builder.createQuery(Post.class);
Root<Post> post = query.from(Post.class);
query.select(post).where(post.get("tag").in("tag1", "tag2", "tag3")); // or pass a tag collection to `in` method
TypedQuery<Post> typedQuery = em.createQuery(query);
List<Post> results = typedQuery.setFirstResult(int1).setMaxResults(int2)
.getResultList();

Thank you very much! Following your instruction, I've done it like this,a little complicated.
public List<Post> findPostBySitePaged(Set sites, Page page) {
List<Post> result = new ArrayList<Post>();
if (sites == null || sites.size() == 0) return result;
try {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> cQuery = builder.createQuery(Long.class);
Root<Post> root = cQuery.from(Post.class);
CriteriaQuery<Long> select = cQuery.select(builder.count(root));
select.where(root.get("site").in(sites));
TypedQuery<Long> typedQuery = em.createQuery(select);
Long t = typedQuery.getSingleResult();
int tot = t.intValue() / page.getPageSize() + ((t.intValue() % page.getPageSize()) == 0 ? 0 : 1);
page.setTotal(tot);
CriteriaQuery<Post> criteriaQuery = builder.createQuery(Post.class);
root = criteriaQuery.from(Post.class);
criteriaQuery.select(root).where(root.get("site").in(sites)).orderBy(builder.desc(root.get("createDate")));
TypedQuery<Post> postQuery = em.createQuery(criteriaQuery);
postQuery.setFirstResult((page.getCurrent() - 1) * (page.getPageSize())).setMaxResults(page.getPageSize());
result = postQuery.getResultList();
} catch (Exception e) {
log.error(e.getMessage());
}
return result;
}

Related

Implement Hibernate with OrderBy

I want to implement Hibernate query with OrderBy clause. I tried this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root).orderBy(root.get("added"));
Query<OrdersModel> q = session.createQuery(query);
cdList = q.getResultList();
But I have to cast the .orderBy like this query.select(root).orderBy((List<javax.persistence.criteria.Order>) root.get("added"));
Do you know what is the proper way to implement this?
I tried also this:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<OrdersModel> query = builder.createQuery(OrdersModel.class);
Root<OrdersModel> root = query.from(OrdersModel.class);
query.select(root);
query.orderBy(builder.desc(root.get("added")));
Query<OrdersModel> q = session.createQuery(query).setMaxResults(5);
cdList = q.getResultList();
But the rows order are not displayed properly. The list is not properly sorted.

Select all records if parameter is null else return specfic item in JPA Criteria query

I am using JPA and I want to write search query for fetching all the records if search field is empty and if search parameter is not null then apply criteria query.
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<String> query = cq.from(String.class);
cq.where(cb.equal(query.get("id"), '1234567'));
TypedQuery<String> q = entityManager.createQuery(cq);
List<String> results = q.getResultList();
return results;
Thanks
I had a solution finally using Criteria API. Have a look at the code below.
public List < Object > retrieveAll(Object obj) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery < Object > cq = cb.createQuery(Object.class);
Root < Object > objQuery = cq.from(Object.class);
List < Predicate > predicates = new ArrayList < Predicate > ();
// You can add as many as Predicate you want.
if (null != obj.getName() && !obj.getName().isEmpty()) {
predicates.add(cb.equal(objQuery.get("Name"), obj.getName()));
}
List < Object > results = new ArrayList < Object > ();
if (!predicates.isEmpty()) {
cq.select(objQuery).where(predicates.toArray(new Predicate[] {}));
cq.orderBy(cb.asc(objQuery.get("Name")));
results = entityManager.createQuery(cq).getResultList();
} else {
results = entityManager.createQuery("from Emplyee ORDER BY Name asc").getResultList();
}
return results;
}

JPA CriteriaBuilder get list entities with criteries

How can I make this select with JPA CriteriaBuilder like hibernate Criteria in my example?
Criteria criteria = getSession().createCriteria(Payment.class);
criteria.setFirstResult(0);
criteria.setMaxResults(1);
criteria.add(Restrictions.eq("statusStepOne", 0));
List list = criteria.list();
and
Criteria criteria = getSession().createCriteria(Payment.class);
criteria.add(Restrictions.eq("oid", oid));
criteria.add(Restrictions.between("dateCreated", Utils.getDateMinus(1), new Date()));
List list = criteria.list();
return (List<Payment>)list;
FIRST QUERY
Criteria criteria = getSession().createCriteria(Payment.class);
criteria.setFirstResult(0);
criteria.setMaxResults(1);
criteria.add(Restrictions.eq("statusStepOne", 0));
List list = criteria.list();
JPA FIRST QUERY
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Payment> query = cb.createQuery(Payment.class);
Root<Payment> p = query.from(Payment.class);
query.select(p);
query.where(cb.equal(p.get("statusStepOne"), 0));
query.setFirstResult(0);
query.setMaxResults(1);
List<Payment> list = query.getResultList();
SECOND QUERY
Criteria criteria = getSession().createCriteria(Payment.class);
criteria.add(Restrictions.eq("oid", oid));
criteria.add(Restrictions.between("dateCreated", Utils.getDateMinus(1), new Date()));
return (List<Payment>) criteria.list(); // I've removed useless asignment
JPA SECOND QUERY
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Payment> query = cb.createQuery(Payment.class);
Root<Payment> p = query.from(Payment.class);
query.select(p);
query.where(cb.equal(p.get("oid"), oid)
.and(cb.between(p.get("dateCreated"), Utils.getDateMinus(1), new Date())));

how do size JPA to Criteriaquery

I have this Java code:
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
I would like to do this a criteria query:
SELECT COUNT(p),pa.nomPays FROM SessionPersonne s JOIN s.personne p ,
p.entreprise e , e.adresse a , a.localite l , l.pays pa , s.session session
WHERE size(s.passageCollection) > 0 GROUP BY pa.nomPays
but how do size(s.passageCollection) > 0 with the critical query ?
Thanks you.
This tutorial explains everything very well.
http://www.baeldung.com/jpa-pagination
Just in case link breaks i'll add a segment and add where the where should be put too
int pageNumber = 1;
int pageSize = 10;
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
Long count = entityManager.createQuery(countQuery).getSingleResult();
CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
Root<Foo> from = criteriaQuery.from(Foo.class);
CriteriaQuery<Foo> select = criteriaQuery.select(from);
select.where(criteriaBuilder.equal(fromRoot.get("entityColumb"), "bar")));
TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
while (pageNumber < count.intValue()) {
typedQuery.setFirstResult(pageNumber - 1);
typedQuery.setMaxResults(pageSize);
System.out.println("Current page: " + typedQuery.getResultList());
pageNumber += pageSize;
}
You can obtain the SIZE for use in Criteria as follows
Expression<Integer> sizeExpr = qb.size(SessionPersonne_.passageCollection)
hence
qb.greaterThan(sizeExpr, 0);

Convert this HQL to Criteria

I have the following HQL statement:
select auditRecord from AuditRecordEntity auditRecord where auditRecord.auditAccount.accountId = :accountId
I'd like to convert it to use the javax.persistence.criteria.CriteriaBuilder, but am unsure what do do, any help is much appreciated!
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery();
Root<AuditRecordEntity> root = query.from(AuditRecordEntity.class);
// what next?
Try this:
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<AuditRecordEntity> criteriaQuery = criteriaBuilder.createQuery(AuditRecordEntity.class);
Root<AuditRecordEntity> root = criteriaQuery.from(AuditRecordEntity.class);
Predicate predicate = criteriaBuilder.equal(root.get("auditAccount").get("accountId"), accountId);
criteriaQuery.where(predicate);
TypedQuery<AuditRecordEntity> query = em.createQuery(criteriaQuery);
return query.getSingleResult();
you can do it like following
public List<UserProfile> getAuditRecords(String acountId) {
Criteria auditCriteria = session.createCriteria(AuditRecordEntity.class);
auditCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
auditCriteria.createCriteria("auditAccount").add(Restrictions.eq("accountId ",acountId));
return auditCriteria .list();
}

Categories

Resources