我有这些 JPA 实体(简化):
@Entity
class Trip {
@Id
Long tripId;
String travelerName;
@OneToMany
List<TripLeg> tripLegs;
}
@Entity
class TripLeg {
@Id
Long tripLegId;
Calendar departureDate;
@ManyToOne
Trip trip;
}
和这个存储库:
interface TripRepository extends JpaRepository<Trip, Long> {
Page<Trip> findByTravelerName(String travelerName, Pageable pageable);
}
有什么方法可以按行程中最早的出发日期对页面响应进行排序吗?是通过查询方法或 JPQL,还是在 Pageable 的排序属性中?
例如,这次旅行:
{
id : 1,
travelerName : "John Doe",
tripLegs : [{
id : 3,
departureDate : 2015-10-03
}]
}
将排序在此之后:
{
id : 2,
travelerName : "John Doe",
tripLegs : [{
id : 1,
departureDate : 2015-10-01
}, {
id : 2,
departureDate : 2015-10-05
}]
}
最佳答案
您可以修改 findByTravelerName 方法来执行此操作
Page<Trip> findByTravelerNameOrderByTripLegsDepartureDateAsc(String travelerName, Pageable pageable);
或者尝试这个查询
SELECT trip FROM Trip as trip join trip.tripLegs as tleg group by tleg.trip_id order by tleg.departureDate ASC
关于java - 按引用实体中的第一项对 JPA 存储库响应进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40134675/