我准备使用 JPA 2.0 的 CriteriaBuilder API 实现如下SQL查询语句:
SELECT * FROM tbl_emp WHERE dept_id = 1 AND group_id IN (1, 3, 5)
我的Java代码大致如下:
public void queryDemo(EntityManager em) {
Integer[] groupIds = { 1, 3, 5 };
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Emp> query = cb.createQuery(Emp.class);
Root<Emp> root = query.from(Emp.class);
query.where(
// dept.id = 1
cb.equal(root.get("dept").get("id"), 1),
// AND groupId IN (1, 3, 5)
cb.in(root.get("groupId").in(groupIds))
);
em.createQuery(query)
.getResultList()
.forEach(emp -> System.out.println(emp.getName()));
}
不幸的是,执行上述代码,结果却抛出如下异常:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: in near line 1, column 154 [select generatedAlias0 from org.lesson001.www.bean.Emp as generatedAlias0 where ( generatedAlias0.dept.id=1 ) and ( generatedAlias0.groupId in (1, 3, 5) in (null) )]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:301)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
请问,在Hibernate中,如何使用 JPA CriteriaBuilder 实现 IN 查询呢?
对了,我使用的是当前最新的 Hibernate 5.4.22.Final。