querysyntaxexception无效路径+jpa+hibernate 5.4

iih3973s  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(420)

我试图根据criteriaquery获取总行数,但遇到了一个异常

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 )]

代码

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

实体

class Product{
Package package;
int quantity;

/// getter setter method

}

class Package{
String id;
String name;
String type

/// getter setter method

}
Map是使用hbm xml文件完成的。
你能告诉我怎么修吗?

ryoqjall

ryoqjall1#

您有两个不同的查询。所以不能对它们使用相同的 predicate ,因为它们有不同的根。
org.hibernate.hql.internal.ast.querysyntaxexception:路径无效:“generatedalias1.package.id”[从com.test.product中选择count(generatedalias0)作为generatedalias0,其中(generatedalias1.package.id like:param0)] generatedAlias1 是的别名 Product 从另一个查询
要使 predicate 可重用,应该创建方法返回 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);
}

然后在查询中使用它

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

相关问题