JPA 2.0 predicate condition lists in query builder - java

Code:
List<Predicate> conditionsList = new ArrayList<Predicate>();
Predicate onStart = criteriaBuilder.greaterThanOrEqualTo(criteriaRoot.get("insertDateTime"), startTradeDate);
Predicate onEnd = criteriaBuilder.lessThanOrEqualTo(criteriaRoot.get("insertDateTime"), endTradeDate);
conditionsList.add(onStart);
conditionsList.add(onEnd);
CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<MyClass> criteriaQuery =
criteriaBuilder.createQuery(MyClass.class);
Root<MyClass> criteriaRoot = criteriaQuery.from(MyClass.class);
criteriaQuery.select(criteriaRoot).where(conditionsList);
The last line above doesn't compile because its expecting the conditionsList object to be a List of Boolean not list of Predicate.
Please advise me on the correct way of adding predicates above to the hibernate criteria?

Convert the List<Predicate> into an array Predicate[] like this:
criteriaQuery.select(criteriaRoot).where(conditionsList.toArray(new Predicate[] {}));

Related

Using Java Predicates in MYSQL AND condition

I have the following java predicate based code that gets a result list from my MYSQL DB:
Root<Person> from = query.from(Person.class);
CriteriaQuery<Person> selectQuery = query.select(from);
List<Person> searchResults = new ArrayList<>();
Predicate jobPredicate = createPersonJobPredicate();
Predicate agePredicate = createPersonAgePredicate(); //currently not used
selectQuery = selectQuery.where(jobPredicate);
searchResults =entityManager.createQuery(selectQuery).setFirstResult(searchRequest.getIndex()).setMaxResults(searchRequest.getSize()).getResultList();
What I want to do is change the above code so that the result list has to match both predicates - e.g. must be job - "doctor" AND age - 45
I have tried combining the predicates as such below, but this always only returns the job predicate:
selectQuery = selectQuery.where(jobPredicate).where(agePredicate);
How can I do so?
Try something like:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
Root<Person> personRoot = criteriaQuery.from(Person.class);
Predicate jobPredicate = criteriaBuilder.equal(personRoot.get("job"), "doctor");
Predicate agePredicate = criteriaBuilder.greaterThan(personRoot.get("age"), 45);
Predicate combinedPredicate = criteriaBuilder.and(jobPredicate, agePredicate);
criteriaQuery.where(combinedPredicate);
List<Person> searchResults =
entityManager.createQuery(criteriaQuery).getResultList();

How to use Criteria And pagination

Hi guys I'm trying to use criteria along with pagination but my code isn't working, here it is :
public Page<Person> getAuthorizationsTest() {
PageRequest pageRequest = new PageRequest(1, 5);
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Person> queryBase = criteriaBuilder.createQuery(Person.class);
Root<Person> root = queryBase.from(Person.class);
List<Predicate> queryConditions = new ArrayList<>();
Predicate predicate = criteriaBuilder.like(root.get("name"), "%[myValue]%");
queryConditions.add(predicate);
queryBase.where(queryConditions.toArray(new Predicate[]{}));
TypedQuery<Person> query = em.createQuery(queryBase);
List<Person> list = query.getResultList();
Page<Person> authorizations = new PageImpl<Person>(list, pageRequest, list.size());
return authorizations;
}
All seems fine, but when I execute it, I receive a list Page with all the results and not only the ones specified in my pageRequest
What am I doing wrong ?
Predicate array and where clause looking properly defined. In these lines:
Predicate predicate = criteriaBuilder.like(root.get("name"),
"%[myValue]%");
queryConditions.add(predicate);
queryBase.where(queryConditions.toArray(new Predicate[]{}));
TypedQuery<Person> query = em.createQuery(queryBase);
Just a reminder. Maybe you need criteriaBuilder.equal instead of criteriaBuilder.like. If you sure what you did you can omitted this reminder.
You need to change following lines like:
query.setFirstResult(Math.toIntExact(pageRequest.getOffset()));
query.setMaxResults(pageRequest.getPageSize());
return new PageImpl<Person>(query.getResultList(), pageRequest, getTotalCount(criteriaBuilder, queryConditions));
Then add getTotalCount method for the sake of consistency.
private Long getTotalCount(CriteriaBuilder criteriaBuilder, Predicate[] predicateArray) {
CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
Root<T> root = criteriaQuery.from(entityType);
criteriaQuery.select(criteriaBuilder.count(root));
criteriaQuery.where(predicateArray);
return entityManager.createQuery(criteriaQuery).getSingleResult();
}
You are not using a paging request :
List list = query.getResultList();
This query will always query for all the results which is very inefficient.
Instead, you should do this the Spring way ie you should use a repository interface that extends a PagingAndSortingRepository (such as the JpaRepository interface).
Then simply use a method to paginate your results such as findAll as stated in the documentation :
PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));

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 criteria builder writing simple query

I want to select from database entities with certain price and with certain type but the result list is empty using criteria builder.I came to this code
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Advert> from = criteriaQuery.from(Advert.class);
Predicate predicate1 = criteriaBuilder.ge(from.get("price"), x1);
Predicate predicate2 = criteriaBuilder.le(from.get("price"), x2);
Predicate predicate4 = criteriaBuilder.like(from.get("type"), type);
criteriaQuery.where(criteriaBuilder.and(predicate1, predicate2, predicate4));
TypedQuery<Object> typedQuery = em.createQuery(criteriaQuery);
List<Object> resultList = typedQuery.getResultList();
But the it returns empty List.How to rewrite it correctly?

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