【问题标题】:Aggregate function on related entities in jpa + Springjpa + Spring中相关实体的聚合函数
【发布时间】:2020-03-16 10:55:57
【问题描述】:

我希望方法的实现应该找到所有项目, 评级低于作为参数传递的。使用与每个项目关联的评论来计算项目评级。

以下是我的课程

@Entity
public class Item {

  @Id
  @GeneratedValue
  private Long id;

  @Column(length = 100)
  @NotEmpty
  private String title;

  @Column(length = 200)
  private String description;

  @OneToMany(mappedBy = "item", cascade = CascadeType.ALL, orphanRemoval = true)
  Set<Review> reviews = new HashSet<>();

  public Item() {
  }

  public Item(String title, String description) {
    this.title = title;
    this.description = description;
  }

  public Long getId() {
    return id;
  }

  public String getTitle() {
    return title;
  }

  public String getDescription() {
    return description;
  }

  public Set<Review> getReviews() {
    return reviews;
  }

}

@Entity
public class Review {

  @Id
  @GeneratedValue
  private Long id;

  @Min(0)
  @Max(10)
  private Integer rating;

  @Length(max=200)
  private String comment;

  @ManyToOne(optional = false)
  private Item item;

  @ManyToOne(optional = false)
  private User author;
}


@Repository
@Transactional
public class ItemRepository {

  @PersistenceContext
  EntityManager entityManager;


 public List<Item> findItemsWithAverageRatingLowerThan(Integer rating) {

    return new ArrayList<>();
  }

我想找到所有具有所提供参数平均评级的项目。 评分的平均值应根据 Item 实体中存在的评论集计算

【问题讨论】:

  • 首先您必须创建rating 字段并为每个Item 计算它。之后,您可以轻松地创建一个 sql 查询来根据给定的条件查找所有 Item's
  • 如何计算查询中每个项目的评分?因为每个项目都有可能的评论和评论评级,所以我必须汇总并找到平均值。这在查询中怎么可能?
  • 使用按项目分组和聚合函数 (AVG),然后过滤掉所需的值。 Spring 完全支持所有语句(jpql、criteria 等)

标签: spring hibernate spring-mvc jpa


【解决方案1】:

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
相关资源
最近更新 更多