How to do between or between query with Criteria API - java

how I can do a query with Criteria API with between or between for this plain sql query:
SELECT * FROM
documents
WHERE (register_date BETWEEN to_date('02.07.2017', 'DD.MM.YYYY') AND to_date('02.07.2018', 'DD.MM.YYYY'))
OR (sign_date BETWEEN to_date('02.07.2017', 'DD.MM.YYYY') AND to_date('02.07.2018', 'DD.MM.YYYY'));
in postgres?
It's not a dublicate because I'm doing a query with TWO between and a question in the link below hasn't criteria api as I can see
I need to make something like this
CriteriaBuilder cb = this.getCSession().getCriteriaBuilder();
CriteriaQuery<Documents> documentsCriteria = cb.createQuery(model_class);
Root<Documents> DocumentsRoot = documentsCriteria.from(model_class);
documentsCriteria.select(DocumentsRoot);
List<Predicate> predicates = new ArrayList<>();
if (register_start_date != null && register_end_date != null) {
predicates.add(cb.between(DocumentsRoot.get("register_date"), register_start_date, register_end_date));
predicates.add(cb.between(DocumentsRoot.get("sign_date"), register_start_date, register_end_date));
}
documentsCriteria.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
List<Order> orderList = new ArrayList<>();
orderList.add(cb.asc(DocumentsRoot.get("register_date")));
orderList.add(cb.asc(DocumentsRoot.get("sign_date")));
documentsCriteria.orderBy(orderList);
Query q = this.getCSession().createQuery(documentsCriteria);
return (List<Documents>) q.getResultList();

you create the criteria based on the entity manager and then you add the between restriction to it.
Criteria criteria = entityManager.unwrap(Session.class).createCriteria(EntityDao.class);
criteria.add(Restrictions.between("your_date_column", date1, date2));
between or between
criteria.add(Restrictions.or(Restrictions.between("your_date_column", date1, date2), Restrictions.between("your_date_column", date3, date4)));

Related

Creating Criteria Query for combine column IN query

I am stuck with this problem
I want to create Criteria Query which translates to
select * from table
where (col1,col2) in ((val1,val2),(val2,val3),....)
I understood how to create it for IN clause on single column
But I want to have IN clause on combination of two columns where values in IN clause is list of tuple of values for these two columns.
Kindly suggest.
EntityManager entityManager;
public List<YourEntity> getEntitiesByParams(Map<Field1Class, Field2Class> params) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<YourEntity> query = cb.createQuery(YourEntity.class);
Root<YourEntity> root = query.from(YourEntity.class);
final List<Predicate> predicates = new ArrayList<>();
for(Entry<Field1Class, Field2Class> entry : params.entrySet()) {
Predicate predicate1 = cb.equal(root.get("field1"), params.getKey());
Predicate predicate2 = cb.equal(root.get("field2"), params.getValue());
predicates.add(
cb.and(predicate1, predicate2)
);
}
query.select(root)
.where(
cb.or(predicates.toArray(new Predicate[predicates.size()]))
);
return entityManager.createQuery(query).getResultList();
}

JPA CriteriaQuery - How to use IN comparison operator

I have two java objects.
User(every user has an index column)
Address( every address has an user_index column too)
I have a List of all the users index list, usersIndexList as given input and I want to fetch all of the address objects based on this usersIndexList. I found an example on another thread. And tried to follow it but it does not work.
JPA CriteriaBuilder - How to use "IN" comparison operator
My code:
List<String> usersIndexList= new ArrayList<String> ();
for (User u : usersList) {
usersIndexList.add(u.getIndex());
}
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<User> subQuery = criteriaBuilder.createQuery(User.class);
Root<User> fromUser= subQuery.from(User.class);
Expression<String> exp = fromUser.get("user_index");
Predicate predicate = exp.in(usersIndexList);
subQuery.where(predicate);
TypedQuery<User> query = getEntityManager().createQuery(subQuery);
return query.getResultList();
But this query is not returning the desired result :(
Can someone please tell me, where I am doing wrong or give me an alternate solutions if its possible via nativequery or namedquery or any other way
As per your question, you want to fetch all of the address objects based on this usersIndexList. But in your code you are selecting User objects, not the Address. Is my understanding Correct? If yes, then please change your root to Address as below -
List<String> usersIndexList= new ArrayList<String> ();
for (User u : usersList) {
usersIndexList.add(u.getIndex());
}
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Address> subQuery = criteriaBuilder.createQuery(Address.class);
Root<Address> fromAddress= subQuery.from(Address.class);
Expression<String> exp = fromAddress.get("user_index");
Predicate predicate = exp.in(usersIndexList);
subQuery.where(predicate);
TypedQuery<Address> query = getEntityManager().createQuery(subQuery);
return query.getResultList();

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())));

JPQL: inner join with group by

I'm trying to retrieve data from database using criteriabuilder. It's working great, query is almost perfect... almost. Unfortunately Java don't want me to use group by or distinct as a result of my query. How to make Java retrieve only unique records? My code is here:
List<Documentation> documentationList = new ArrayList<>();
DatabaseConnector dc = new DatabaseConnector();
List<Predicate> criteria = new ArrayList<Predicate>();
EntityManager em = dc.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Documentation> select = builder.createQuery(Documentation.class);
Root<Documentation> u = select.from(Documentation.class);
Join<Documentation, DocumentationUser> du = u.join("documentationUserCollection", JoinType.INNER);
javax.persistence.Query q = em.createQuery(select);
select.groupBy(u.<String>get("documentationId"));
select.distinct(true);
documentationList = q.setMaxResults(pageSize).setFirstResult(first).getResultList();
Try swapping 2 lines lower the line that creates the query:
select.groupBy(u.<String>get("documentationId"));
select.distinct(true);
javax.persistence.Query q = em.createQuery(select);

ORDER BY using Criteria API

When I write a HQL query
Query q = session.createQuery("SELECT cat from Cat as cat ORDER BY cat.mother.kind.value");
return q.list();
Everything is fine. However, when I write a Criteria
Criteria c = session.createCriteria(Cat.class);
c.addOrder(Order.asc("mother.kind.value"));
return c.list();
I get an exception org.hibernate.QueryException: could not resolve property: kind.value of: my.sample.data.entities.Cat
If I want to use Criteria and Order, how should I express my "order by"?
You need to create an alias for the mother.kind. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
This is what you have to do since sess.createCriteria is deprecated:
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<User> q = builder.createQuery(User.class);
Root<User> usr = q.from(User.class);
ParameterExpression<String> p = builder.parameter(String.class);
q.select(usr).where(builder.like(usr.get("name"),p))
.orderBy(builder.asc(usr.get("name")));
TypedQuery<User> query = getSession().createQuery(q);
query.setParameter(p, "%" + Main.filterName + "%");
List<User> list = query.getResultList();
It's hard to know for sure without seeing the mappings (see #Juha's comment), but I think you want something like the following:
Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();
You can add join type as well:
Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);
For Hibernate 5.2 and above, use CriteriaBuilder as follows
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother"); // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Categories

Resources