如何将以下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;
}
}
答案 0 :(得分:0)
查看此问题以讨论实体的检索,您无法避免使用投影,但我认为它可以满足您的需求。详细看看杰罗姆的回答:
https://stackoverflow.com/a/29838324/6827719
这是一个非常简单的问题,用户询问如何通过投影订购: