SpringData/Hibernate: Sort enum by it's field

Viewed 2221

I have small problem with sorting enums by custom rule with springdata/hibernate.

A have an enum called let's say: DeviceState, which has its own priority field.

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;
    }
}

The enum is used by DeviceEntity:

@Entity
public class Device implements Serializable {

    // .... other fields

    @Enumerated(EnumType.STRING)
    private DeviceState state;

    // ....
}

I use SpringData/Repository to get entities from database, I have used findAll(specification, pageable) method from org.springframework.data.repository.Respository class.

Page<Device> pagedDevices = deviceRepository.findAll(DeviceSpecifications.findByFilter(filter), pageable);

And if my request cointains sort=state,asc it will return the Devices sorted by state - alphabetically, but I would like to use priority field as sort criteria instead.

What have i tried: change @Enumerated(STRING) to @Enumerated(ORIDINAL) - but this cannot happen this is production working system with existing data, there are several devices which are using by external system and my project needs String values.

Control sort order of Hibernate EnumType.STRING properties but i cannot add any new column since I already have production data and all enum values are persisted as String.

I also have tried some "workarounds" with wrapping Page result - but these are just workarounds not pure solutions :)

Any clue, help? idea? Please keep in mind that this is production working system and I cannot do any "fireworks".

1 Answers
Related