【问题标题】:SpringData/Hibernate: Sort enum by it's fieldSpring Data/Hibernate:按字段对枚举进行排序
【发布时间】: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


    【解决方案1】:
    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
    

    【讨论】:

    • 我之前想使用该解决方案,但我使用 spring data / repository findAll(specification, pageable) 方法,我唯一可以自定义的是规范(查询过滤器)。可分页上下文(第一个结果、最大结果、大小、排序等)由 spring-data 维护 - 所以我无法修改它。所以这个解决方案可能没问题 - 但在我的情况下不是。无论如何,谢谢;) ps:我还尝试使用javax.persistance中的@Formula注释。失败:(
    • 添加到@siepyta 评论,您实际上可以将所有排序逻辑移动到使用标准构建器进行查询。在切换到弹簧数据之前在项目上有这个。长得很丑……
    猜你喜欢
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 2013-07-10
    • 2015-03-24
    • 1970-01-01
    相关资源
    最近更新 更多