如何在Hibernate hql中获取具有最大值的对象?

时间:2015-11-16 02:22:12

标签: hibernate hibernate-criteria

我正在使用Hibernate进行查询,以下是查询

List<ArticleP> articleP = session.createQuery("select ap, max(ap.lastPrice.price) from ArticleP ap "
                + "where ap.stock > 0 and ap.article.category.idCategory = :idCategory "
                + "group by ap.article, ap.prov "
                + "order by ap.article.desc ASC")
                .setProperties(category)
                .list();

我得到一个包含一个对象和一个max double的多维数组,但我想得到一个具有最大值的对象数组,如下所示

List<ArticleP> articleP = session.createQuery("from ArticleP ap "
                    + "where ap.stock > 0 and ap.article.category.idCategory = :idCategory and max(ap.lastPrice.price) "
                    + "group by ap.article, ap.prov "
                    + "order by ap.article.desc ASC")
                    .setProperties(category)
                    .list();

我知道最后一个查询是不可能的,也不知道如何获得所需的数据。

提前致谢。

1 个答案:

答案 0 :(得分:0)

Ypu可以定义子查询并像这样使用IN

List<ArticleP> articleP = session.createQuery("select ap, max(ap.lastPrice.price) from ArticleP ap "
            + "where ap.stock > 0 and ap.article.category.idCategory = :idCategory "
            + "and ap.id IN (select max(ap.lastPrice.price) from ArticleP ap 
            + "              group by ap.article, ap.prov "
            + "              order by ap.article.desc ASC)")
            .setProperties(category)
            .list();from phone p where p.id not in