使用 Spring Pageable 对动态计算值进行排序
Sorting of dynamically computed values using Spring Pageable
我有以下实体:
@Entity
@Table(name = "events")
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private OffsetDateTime startTime;
private OffsetDateTime endTime;
private Long duration;
public void setDuration() {
if (Objects.nonNull(startTime) && Objects.nonNull(endTime)) {
duration = Duration.between(startTime, endTime).toSeconds();
}
}
}
表示系统中的某个事件可能会持续一段时间。创建新实体时,startTime
设置为 OffsetDateTime.now()
。 duration
属性 在事件结束时设置 endTime
。
当获取 Event
个实体时,duration
被动态计算为 Duration.between(startTime, OffsetDateTime.now()).toSeconds()
。
我正在尝试使用 Specification
和 Pageable
对象获取 Event
实体,以便轻松对对象进行排序:
eventRepository.findAll(Specification, Pageable)
如您所想,排序对未完成的事件不起作用(因为 DB 中的 duration
设置为 null
)。从数据库中获取 属性 时是否有可能以某种方式设置默认值?
您可以添加一个 @Formula("coalesce(duration, 0)") int durationForSort;
字段并根据需要排序。
我有以下实体:
@Entity
@Table(name = "events")
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private OffsetDateTime startTime;
private OffsetDateTime endTime;
private Long duration;
public void setDuration() {
if (Objects.nonNull(startTime) && Objects.nonNull(endTime)) {
duration = Duration.between(startTime, endTime).toSeconds();
}
}
}
表示系统中的某个事件可能会持续一段时间。创建新实体时,startTime
设置为 OffsetDateTime.now()
。 duration
属性 在事件结束时设置 endTime
。
当获取 Event
个实体时,duration
被动态计算为 Duration.between(startTime, OffsetDateTime.now()).toSeconds()
。
我正在尝试使用 Specification
和 Pageable
对象获取 Event
实体,以便轻松对对象进行排序:
eventRepository.findAll(Specification, Pageable)
如您所想,排序对未完成的事件不起作用(因为 DB 中的 duration
设置为 null
)。从数据库中获取 属性 时是否有可能以某种方式设置默认值?
您可以添加一个 @Formula("coalesce(duration, 0)") int durationForSort;
字段并根据需要排序。