Search code examples
javajpahql

Group and sort a collection of collections using JPA


I am looking to make a REST controller that will return a sorted list of various objects.

I have created a DTO to hold these collections like the following, but this will not work as it will group by entity:

public class AllReportsDTO {

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

I then have the following Domain objects

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

And one for each Report.

What I want to do is create an endpoint that will return a list of all these reports but in order of time of the report and not grouped by report. How can I achieve this?

I have tried writing it in the repository with a HQL query and grouping by time, but the issue is that each time field has a different name in each report which I can not alter due to this system being used in other places.


Solution

  • I wouldn't try a pure HQL solution, or a solution from your ORM. I would go to the Java way.

    1. Add an interface

      public interface ITimedReport {
          ZonedDateTime getTime();
      }
      
    2. Make all your report class implements this interface by returning their own timestamp
    3. Add a method getAllReports on AllReportsDTO. This method should fill a List<ITimedReport> with all reports, and then sort the list with a Comparator<ITimedReport>. This comparator would rely on the getTime() to compare.

    You can add anything meaningfull for a report in the interface, like a getTitle, getDescription, ...