【发布时间】:2016-07-01 03:37:59
【问题描述】:
我在使用 springdata/hibernate 的自定义规则对枚举进行排序时遇到了小问题。
有一个枚举,比如说:DeviceState,它有自己的优先级字段。
public enum DeviceState {
ON(4), OFF(3), UPDATE(2), CRITICAL(0), WARNING(1);
private final int priority;
private DeviceState(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
}
枚举被DeviceEntity使用:
@Entity
public class Device implements Serializable {
// .... other fields
@Enumerated(EnumType.STRING)
private DeviceState state;
// ....
}
我使用 SpringData/Repository 从数据库中获取实体,我使用了 org.springframework.data.repository.Respository 类中的 findAll(specification, pageable) 方法。
Page<Device> pagedDevices = deviceRepository.findAll(DeviceSpecifications.findByFilter(filter), pageable);
如果我的请求包含 sort=state,asc,它将返回按状态排序的设备 - 按字母顺序,但我想使用优先级字段作为排序标准。
我尝试了什么: 将@Enumerated(STRING) 更改为@Enumerated(ORIDINAL) - 但这不可能发生,这是具有现有数据的生产工作系统,外部系统正在使用多个设备,我的项目需要字符串值。
Control sort order of Hibernate EnumType.STRING properties 但我无法添加任何新列,因为我已经拥有生产数据并且所有枚举值都以字符串形式保存。
我还尝试了一些包装 Page 结果的“变通办法” - 但这些只是变通办法,而不是纯粹的解决方案 :)
任何线索,帮助?主意? 请记住,这是生产工作系统,我不能做任何“烟花”。
【问题讨论】:
标签: java hibernate sorting enums spring-data