使用JPA进行分组并分类集合的集合



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

我创建了一个DTO来保存以下内容,但这将不起作用,因为它将按实体进行分组:

public class AllReportsDTO {
private List<AReport> aReports;
private List<BReport> bReports;
private List<CReport> cReports;
...
}

i然后具有以下域对象

@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;

,每个报告一个。

我要做的是创建一个端点,该端点将返回所有这些报告的列表,但按报告的时间顺序而不是按报告进行分组。我该如何实现?

我尝试使用HQL查询和按时间进行分组的存储库中,但问题是,每个报告中的每个报告都有不同的名称,因为该系统在其他地方使用了,我无法更改。

您可以创建对设置进行排序的methode。尝试熟练这个

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

我不会尝试纯HQL解决方案或您的ORM解决方案。我会去Java Way。

  1. 添加接口

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

您可以在接口中的报告中添加任何有意义的报告,例如getTitle,getDescription,...

最新更新