如何在投影中添加具有嵌套实体的完整实体。
问题是我想将给定的HQL转换为Criteria API。
SELECT p FROM Product p LEFT JOIN p.reviews r GROUP BY p ORDER BY r.rating ASC
考虑1产品有很多评论。 (一对多关系)
此外,我不愿意使用Projection,因为Product class有其他实体,这些实体都是热切地获取的。例如,产品类有品牌实体。 (多对一)。
如果可能,我需要最少量的投影代码。
产品类
@Entity
public class Product {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(mappedBy = "product")
private Review review;
@ManyToOne
private Brand brand;
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 Review getReview() {
return review;
}
public void setReview(Review review) {
this.review = review;
}
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
}
评分
@Entity
public class Review {
@Id
@GeneratedValue
private long id;
private String text;
private int rating;
@ManyToOne
private Product product;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
答案 0 :(得分:0)
如果问题出现在插入上,则必须在父类上配置级联(CascadeType)。 http://docs.oracle.com/javaee/6/tutorial/doc/bnbqa.html
如果查询是您所需要的,这可以作为连接+订单查询的示例:
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> product= cq.from(Product.class);
Join<Product, Review> review = product.join("review");
cq.select(product);
cq.groupBy(review.get("rating"));
cq.orderBy(cb.asc(cb.avg(review.get("rating"))));