HQL将复杂的hql转换为条件

时间:2014-03-19 16:14:01

标签: java hibernate criteria-api

HQL

Query query = getSession()
        .createQuery(
                "select com from News as news " +
                "join news.comments as com " +
                "where news.id = :id " +
                "order by com.addDate desc"
        );
query.setParameter("id", id);

上面的HQL工作正常。想要改变标准api。我无法做到。请帮忙

1 个答案:

答案 0 :(得分:1)

我想你可以尝试这样的事情。

    Criteria c  = createCriteria(News.class);
    c.add(Restrictions.idEq(id));
    Criteria cComment = c.createCriteria("comments",c);
    cComment.addOrder(Order.desc("addDate"));
    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("c.id"),"id");
    projections.add(Projections.property("c.addDate"),"addDate");
    //Other Properties...
    c.setProjection(projections)
    c.setResultTransformer(Transformers.aliasToBean(Comment.class))
    List<News> list = c.list();

请注意,不推荐使用Hibernate Criteria API以支持JPA Criteria API