使用 JPA 对集合的集合进行分组和排序

Group and sort a collection of collections using JPA

我希望制作一个 REST 控制器,它将 return 各种对象的排序列表。

我创建了一个 DTO 来保存这些集合,如下所示,但这不起作用,因为它将按实体分组:

public class AllReportsDTO {

private List<AReport> aReports;
private List<BReport> bReports;
private List<CReport> cReports;
...
}

然后我有以下域对象

@Entity
@Table(name = "a_report")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AReport implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "title")
private String title;

@Column(name = "description")
private String description;

@Column(name = "time_of_report")
private ZonedDateTime timeOfReport;

每份报告一份。

我想要做的是创建一个端点,它将 return 所有这些报告的列表,但按报告的时间顺序排列,而不是按报告分组。我怎样才能做到这一点?

我已经尝试使用 HQL 查询将其写入存储库并按时间分组,但问题是每个时间字段在每个报告中都有不同的名称,由于该系统正在其他应用程序中使用,我无法更改地点。

您可以创建对集合进行排序的方法。尝试改编这个

Collections.sort( aReports, new Comparator<Object>() {
  public int compare(MyObject o1, Object o2) {
      return o1.getTimeOfReport().compareTo(o2.getTimeOfReport());
  }
});

我不会尝试纯 HQL 解决方案或来自您的 ORM 的解决方案。我会选择 Java 方式。

  1. 添加接口

    public interface ITimedReport {
        ZonedDateTime getTime();
    }
    
  2. 让你的所有报告class通过返回他们自己的时间戳来实现这个接口
  3. AllReportsDTO 上添加方法 getAllReports。 此方法应该用 List<ITimedReport> 填充所有报告,然后用 Comparator<ITimedReport> 对列表进行排序。该比较器将依赖 getTime() 进行比较。

您可以在界面中为报告添加任何有意义的内容,例如 getTitle、getDescription,...