简体   繁体   中英

QuerySyntaxException Invalid path + JPA + Hibernate 5.4

I am trying to get the total row count based on the CriteriaQuery but got an exception

org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.package.id' [select count(generatedAlias0) from com.test.Product as generatedAlias0 where ( generatedAlias1.package.id like :param0 )]

Code

CriteriaBuilder cb = session().getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root<Product> entity = query.from(Product.class);
query.where(where_clause);

CriteriaQuery<Long> queryCount = cb.createQuery(Long.class);
Root<Product> entity = queryCount.from(query.getResultType());
queryCount.where(query.getRestriction()) -- this is where the problem is creating

Entity

class Product{
Package package;
int quantity;

/// getter setter method

}

class Package{
String id;
String name;
String type

/// getter setter method

}

mapping is done using hbm xml file.

can you please let me know how to fix it ?

You have two different queries. So you can't use the same predicate for both of them, because they have different roots.

org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'generatedAlias1.package.id' [select count(generatedAlias0) from com.test.Product as generatedAlias0 where ( generatedAlias1.package.id like :param0 )]

generatedAlias1 is alias for Product from another query

To make the predicate reusable you should create method returns predicate

Predicate getPredicate(Root<Product> root, CriteriaBuilder builder, Parameter param) {
   // returns predicate using root, builder and param you need
   return builder.equal(root.get("fieldName"), param);
}

And then use it in queries

CriteriaBuilder cb = session().getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root<Product> entity = query.from(Product.class);
query.where(getPredicate(entity, cb, param));

CriteriaBuilder cbCount = session().getCriteriaBuilder();
CriteriaQuery<Long> queryCount = cbCount.createQuery(Long.class);
Root<Product> entityCount = queryCount.from(Product.class);
queryCount.where(getPredicate(entityCount, cbCount, param));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM