标准Builder Hibernate 5中的相关查询

时间:2018-01-20 09:09:07

标签: hibernate hibernate-criteria criteria-api correlated-subquery

我想只提取那些具有最新版内容

的列

内容实体将ContentPK作为主键(id,version) 沿着本机关联查询的行 select * from content c1 where content.version = (select max(version) from content c2 where c2.id=c1.id)

我想用CriteriaBuilder实现这个目标

CriteriaBuilder criteriaBuilder = currentSession().getCriteriaBuilder();
        CriteriaQuery<Content> parentQuery = criteriaBuilder.createQuery(Content.class);
        Root<Content> root = parentQuery.from(Content.class);
        parentQuery.select(root);
        Subquery<Integer> subquery = parentQuery.subquery(Integer.class);
        Root<Content> subRoot = subquery.correlate(root);
        subquery.select(criteriaBuilder.max(subRoot.get(Content_.contentPK).get(ContentPK_.version)));
        subquery.where(criteriaBuilder.equal(subRoot.get(Content_.contentPK).get(ContentPK_.id), root.get(Content_.contentPK).get(ContentPK_.id)));
        parentQuery.where(criteriaBuilder.equal(root.get(Content_.contentPK).get(ContentPK_.version), subquery));
        return currentSession().createQuery(parentQuery).list();

给出此错误

  

引起:org.hibernate.hql.internal.ast.QuerySyntaxException:从com.m3.db.content.Content中选择generatedAlias0作为generatedAlias0,其中generatedAlias0.contentPK.version =(select max(generatedAlias0.contentPK.version)from其中generatedAlias0.contentPK.id = generatedAlias0.contentPK.id)]

如何解决此错误?

0 个答案:

没有答案