I have a query with some predicates, I need to count total records for paging.
Currently, what I'm doing is declare 2 roots for the query to get result list (1) and the count query (2), then with each predicate, duplicate it with different root like this
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<A> root = cq.from(A.class);
CriteriaQuery<Long> cq = cb.createQuery(A.class);
Root<A> rootCount = countQuery.from(A.class);
List<Predicate> predicates = new ArrayList<>();
List<Predicate> predicatesCount = new ArrayList<>();
Predicate p = cb.equal(root.get(A.ID), 1);
predicates.add(p);
Predicate p1 = cb.equal(rootCount.get(A.ID), 1);
predicatesCount.add(p1);
...
// execute both query to get result
So the question is:
Is it possible to create count query from query (1)? Or something to reuse the predicates with count query?
Thanks for reading!
The below example showcases setting up a criteria builder/predicate restrictions, then reusing that to do a count query as well.
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<EntityStub> criteriaQuery = builder.createQuery(EntityStub.class);
Root<EntityStub> entity_ = criteriaQuery.from(EntityStub.class);
entity_.alias("entitySub"); //assign alias to entity root
criteriaQuery.where(builder.equal(entity_.get("message"), "second"));
// Generic retrieve count
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
Root<T> entity_ = countQuery.from(criteriaQuery.getResultType());
entity_.alias("entitySub"); //use the same alias in order to match the restrictions part and the selection part
countQuery.select(builder.count(entity_));
Predicate restriction = criteriaQuery.getRestriction();
if (restriction != null) {
countQuery.where(restriction); // Copy restrictions
}
Long count = entityManager.createQuery(countQuery).getSingleResult();
See if that helps you, take note of the root alias, and when doing a Count Query, make sure the Entity class type is Long.class
https://forum.hibernate.org/viewtopic.php?p=2471522#p2471522
You could use Blaze-Persistence to generate the count query for you as it's not that easy to implement such a count query efficiently.
Blaze-Persistence is a library that works on top of JPA/Hibernate and adds support for advanced SQL constructs, rich pagination support and much more. It also has a JPA Criteria implementation which you can use as a drop-in replacement. You can then convert this query to a Blaze-Persistence Core query builder which allows to generate a count query: https://github.com/Blazebit/blaze-persistence#jpa-criteria-api-quick-start
I think this guy answered your question with its utility class like so :
Long count = JpaUtils.count(entityManager, criteriaQuery);
https://stackoverflow.com/a/9246377/5611906
Related
I have the below piece of the code to get count query form the original query.
But this is the line causing the issue at compile time.
countQuery.from(sqmSubQuery);
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
SqmSubQuery sqmSubQuery = (SqmSubQuery<Tuple>) countQuery.subquery(Tuple.class);
SqmSelectStatement sqmOriginalQuery = (SqmSelectStatement) query;
SqmQuerySpec sqmOriginalQuerySpec = sqmOriginalQuery.getQuerySpec();
sqmSubQuery.setQueryPart(sqmOriginalQuerySpec.copy(SqmCopyContext.simpleContext()));
Root<T> subQuerySelectRoot = (Root<T>) sqmSubQuery.getRoots().iterator().next();
sqmSubQuery.multiselect(subQuerySelectRoot.get("id").alias("id"));
countQuery.select(builder.count(builder.literal(1)));
countQuery.from(sqmSubQuery);
Based on you comment you want to select the distinct count of all employee types. The query you provided should be equivalent to SELECT COUNT(DISTINCT employee_type) FROM Employee.
This can be written in JPA as shown below:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
Root<Employee> employeeRoot = countQuery.from(Employee.class);
countQuery.select(builder.countDistinct(employeeRoot.get("type")));
Long count = entityManager.createQuery(countQuery).getSingleResult();
where type is the name of the property that maps to the column employee_type
The type org.hibernate.query.criteria.JpaSelectCriteria declares this method:
<X> JpaDerivedRoot<X> from(jakarta.persistence.criteria.Subquery<X> subquery);
which is the one you need to call if you're trying to use a subquery in the from clause.
And SqmSelectStatement implements JpaSelectCriteria. (It is also the object which implements jakarta.persistence.criteria.CriteriaQuery.)
So you can cast any CriteriaQuery to JpaSelectCriteria and call from():
CriteriaQuery<Thing> query = ... ;
Subquery<OtherThing> subquery = ... ;
((JpaSelectCriteria<Thing>) query).from(subquery);
or whatever (I did not test this code).
SQL (that works in database):
SELECT ffm.REPORTING_PERIOD, count(DISTINCT ffm.FI_MESSAGE_ID), count(ffa.FI_ACCOUNT_ID) FROM RAZV.FINTAEOI2_FI_MESSAGE ffm
JOIN razv.FINTAEOI2_FI_MESSAGE_FI ffmf ON ffm.FI_MESSAGE_ID = ffmf.FI_MESSAGE_ID
JOIN razv.FINTAEOI2_FI_ACCOUNT ffa ON ffmf.FI_MESSAGE_FI_ID = ffa.FI_MESSAGE_FI_ID
WHERE ffm.REPORTING_PERIOD = '2020-12-31'
GROUP BY ffm.REPORTING_PERIOD
There will be 6 possible WHERE statements so I decided to use TypedQuery to simplify conditions appending.
Problem is; How can I include count into TypedQuery select and is it even possible? If not, what would be the best way except making multiple queries? If only way is multiple queries, how do I fill the dto?
This is my query where I should include count.
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<ReportListDto> cq = cb.createQuery(ReportListDto.class);
Root<FiMessage> fromFIMessage = cq.from(FiMessage.class);
Join<FiMessage, FiMessageFi> fiMessageFi = fromFIMessage.join("fintaeoi2FiMessageFis", JoinType.INNER);
Join<FiMessageFi, FiAccount> fiAccount = fiMessageFi.join("fintaeoi2FiAccounts", JoinType.INNER);
List<Predicate> conditions = new ArrayList<Predicate>();
`**TypedQuery<ReportListDto> query = entityManager.createQuery(
cq.multiselect(
fromFIMessage.get("reportingPeriod"),
fromFIMessage.get("fiMessageId"),
fiAccount.get("fiAccountId"))
.where(conditions.toArray(new Predicate[] {})));**
List<ReportListDto> result = query.getResultList();
`
result of above is
[results without count included](https://i.stack.imgur.com/MO7Zk.png)
but i need
[result ash it should be with applying count in typedquery](https://i.stack.imgur.com/gqnC9.png)
So reporting period is fine and I need distinct count for messageId and count for accountId.
Thank you for your answers.
The answer is
TypedQuery<ReportListDto> query = entityManager.createQuery(cq.multiselect(fromFIMessage.get("reportingPeriod"), cb.countDistinct(fromFIMessage.get("fiMessageId")), cb.count(fiAccount.get("fiAccountId")))
.where(conditions.toArray(new Predicate[] {})));
I've used hibernate for a long, now i started using JPA and i can't find a short way to write a simply select in less than seven lines (the use of criteria is a must in this project), is there a shorter way to build this query?
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
Root<Transaction> root = cq.from(Transaction.class);
Collection<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(cb.equal(root.get("originalOperationId"), originalOperationId));
cq.where(predicates.toArray(new Predicate[predicates.size()]));
List<Transaction> resultado = em.createQuery(cq).getResultList();
return resultado;
I'm trying to delete a bunch of objects with one query using the CriteriaBuilder API. I'm looking for something like this select:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> query = criteriaBuilder.createQuery(entityClass);
Root<T> root = query.from(entityClass);
query.select(root).where(/*some condition*/);
return entityManager.createQuery(query).getResultList();
but then a delete instead of a select. As far as I can see, there's no remove or delete method on CriteriaQuery. Is it possible using this API?
I can of course execute the select, then call entityManager.remove(object) for each result, but that feels very inefficient.
Try this:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaDelete<SomeClass> query = criteriaBuilder.createCriteriaDelete(SomeClass.class);
Root<SomeClass> root = query.from(SomeClass.class);
query.where(root.get("id").in(listWithIds));
int result = entityManager.createQuery(query).executeUpdate();
The where clause can laso look like this:
query.where(criteriaBuilder.lessThanOrEqualTo(root.get("id"), someId));
in JPA 2.1, there are Criteria APIs exactly as what you want.it looks like this:
CriteriaBuilder cBuilder = em.getCriteriaBuilder();
CriteriaDelete<T> cq = cBuilder.createCriteriaDelete(entityClass);
Root<T> root = cq.from(entityClass);
cq.where(/*some codition*/);
int result = em.createQuery(cq).executeUpdate();
you can refert to JPA 2.1 SPEC and API here
When using the JPA Criteria API, what is the advantage of using a ParameterExpression over a variable directly? E.g. when I wish to search for a customer by name in a String variable, I could write something like
private List<Customer> findCustomer(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> criteriaQuery = cb.createQuery(Customer.class);
Root<Customer> customer = criteriaQuery.from(Customer.class);
criteriaQuery.select(customer).where(cb.equal(customer.get("name"), name));
return em.createQuery(criteriaQuery).getResultList();
}
With parameters this becomes:
private List<Customer> findCustomerWithParam(String name) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> criteriaQuery = cb.createQuery(Customer.class);
Root<Customer> customer = criteriaQuery.from(Customer.class);
ParameterExpression<String> nameParameter = cb.parameter(String.class, "name");
criteriaQuery.select(customer).where(cb.equal(customer.get("name"), nameParameter));
return em.createQuery(criteriaQuery).setParameter("name", name).getResultList();
}
For conciseness I would prefer the first way, especially when the query gets longer with optional parameters. Are there any disadvantages of using parameters like this, like SQL injection?
you can use ParameterExpression like this:
assume that you have some input filter, an example could be this:
in your query you have to check the value of a fiscal Code.
let's start:
first of all create criteriaQuery and criteriaBuilder and root
CriteriaBuilder cb = _em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<RootEntity> soggettoRoot = cq.from(RootEntity.class);
1) inizialize a predicateList(use for where clause) and a paramList(use for param)
Map<ParameterExpression,String> paramList = new HashMap();
List<Predicate> predicateList = new ArrayList<>();
2 )check if the input is null and create predicateList and param
if( input.getFilterCF() != null){
//create ParameterExpression
ParameterExpression<String> cf = cb.parameter(String.class);
//if like clause
predicateList.add(cb.like(root.<String>get("cf"), cf));
paramList.put(cf , input.getFilterCF() + "%");
//if equals clause
//predicateList.add(cb.equal(root.get("cf"), cf));
//paramList.put(cf,input.getFilterCF()());
}
3) create the where clause
cq.where(cb.and(predicateList.toArray(new Predicate[predicateList.size()])));
TypedQuery<Tuple> q = _em.createQuery(cq);
4) set param value
for(Map.Entry<ParameterExpression,String> entry : paramList.entrySet())
{
q.setParameter(entry.getKey(), entry.getValue());
}
When using a parameter, likely (dependent on JPA implementation, datastore in use, and JDBC driver) the SQL will be optimised to a JDBC parameter so if you execute the same thing with a different value of the parameter it uses the same JDBC statement.
SQL injection is always down to the developer as to whether they validate some user input that is being used as a parameter.