我在使用 springdata/hibernate 按自定义规则对枚举进行排序时遇到了小问题。
A 有一个名为 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但我无法添加任何新列,因为我已经拥有生产数据并且所有枚举值都作为字符串保留。
我也尝试过一些包装页面结果的“变通办法”——但这些只是变通办法,而不是纯粹的解决方案:)
任何线索,帮助?主意? 请记住,这是生产工作系统,我不能做任何“烟花”。
最佳答案
order by case
when state = 'CRITICAL' then 0
when state = 'WARNING' then 1
when state = 'UPDATE' then 2
when state = 'OFF' then 3
when state = 'ON' then 4
end
关于java - Spring 数据/hibernate : Sort enum by it's field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36015661/