java - Jpa criteria count -


i have new problem. created code, generate predicate, client request. initializing part:

 criteriabuilder = entitymanager.getcriteriabuilder();  criteriaquery = criteriabuilder.createquery(classentity);  root = criteriaquery.from(classentity); 

when want list entities work great:

criteriaquery.select(root).where(predicate); entitymanager.createquery(criteriaquery).getresultlist(); 

but when want count entities:

criteriaquery<long> cq = criteriabuilder.createquery(long.class); cq.select(criteriabuilder.count(root)).where(predicate); system.err.println("eee : " +entitymanager.createquery(cq).getsingleresult()); 

it fall exception

java.lang.illegalargumentexception: error occurred validating criteria caused by: java.lang.illegalstateexception: no criteria query roots specified

probably should said, root generate dynamically joins:

private path parsefield(string field) {     path path = null;      if (field.contains(".")) {          string [] split = field.split("\\.");         join join = root.join(split[0],jointype.inner);          (int =1; < split.length-1; i++) {             join = join.join(split[i],jointype.inner);         }          path = join.get(split[split.length-1]);      } else {         path = root.get(field);     }     return path; } 

if replace

cq.select(criteriabuilder.count(root)).where(previouspredicate); 

on

cq.select(criteriabuilder.count(cq.from(classentity))).where(previouspredicate); 

i fail exception

 org.hibernate.hql.ast.querysyntaxexception: invalid path: 'generatedalias1.(somefieldname)'  

it works fine me:

criteriabuilder cb = em.getcriteriabuilder(); criteriaquery<long> q = cb.createquery(long.class); root<a> r = q.from(a.class); mapjoin<a, string, string> m = r.joinmap("metadata"); q.select(cb.count(r)).where(cb.equal(m.key(), "a")); long rs = em.createquery(q).getsingleresult(); 

so, it's hard see doing wrong without mcve.


Comments