在没有投影的情况下,在Hibernate Criteria API中使用order by with aggregate functions

时间:2016-10-07 13:23:44

标签: hibernate hql jpql hibernate-criteria criteria-api

如何将以下SQL查询转换为Hibernate Criteria API和HQL。

SELECT product.* FROM product JOIN product_likes ON product_likes.product = product.id 
    GROUP BY product.id 
    ORDER BY COUNT(product_likes.id) DESC

在列表中我只想要产品类实体。

产品和产品喜欢有一对多的关系。

类产品

@Entity
public class Product {

    @Id
    @GeneratedValue
    private long id;

    private String name;

    @OneToMany(mappedBy = "product")
    private ProductLikes productLikes;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ProductLikes getProductLikes() {
        return productLikes;
    }

    public void setProductLikes(ProductLikes productLikes) {
        this.productLikes = productLikes;
    }

}

Class ProductLikes

@Entity
public class ProductLikes {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    private Product product;

    @ManyToOne
    private User user;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

1 个答案:

答案 0 :(得分:0)

查看此问题以讨论实体的检索,您无法避免使用投影,但我认为它可以满足您的需求。详细看看杰罗姆的回答:

https://stackoverflow.com/a/29838324/6827719

这是一个非常简单的问题,用户询问如何通过投影订购:

How to apply order on hibernate projection result