Control sort order of Hibernate EnumType.STRING properties

断了今生、忘了曾经 提交于 2019-12-05 08:14:35
Pascal Thivent

So I'm thinking of switching to EnumType.STRING to not have to remap ordinal values in the database again. But if I do this, then how do I sort properly? The alphabetical order of the enum strings is not the order I need.

I personally totally avoid using the evil EnumType.ORDINAL as just changing the order of the constants would brake the persistence logic. Evil. That said, EnumType.STRING is indeed not always appropriate.

In your case, here is what I would do (with standard JPA): I would persist an int at the entity level and perform the enum conversion in getter/setters. Something like this. First, the enum:

public enum Status {
    PLANNING("Planning", 100),
    DEVELOPMENT("Development", 200),
    PRODUCTION("Production", 300);

    private final String label;
    private final int code;

    private Status(String label, int code) {
        this.label = label;
        this.code = code;
    }

    public int getCode() { return this.code; }

    private static final Map<Integer,Status> map;
    static {
        map = new HashMap<Integer,Status>();
        for (Status v : Status.values()) {
            map.put(v.code, v);
        }
    }
    public static Status parse(int i) {
        return map.get(i);
    }
}

So basically, the idea is to be able to get a Status by its code. And we keep some room between constants so that adding values is possible (it's not pretty but, well, it will work and should be safe for some time).

And then in the entity:

@Entity
public class Project {
    private Long id;
    private int statusCode;

    @Id @GeneratedValue
    public Long getId() {
        return this.id;
    }
    private void setId(Long id) {
        this.id = id;
    }

    @Transient
    public Status getStatus () {
        return Status.parse(this.statusCode);
    }
    public void setStatus(Status status) {
        this.statusCode = status.getCode();
    }

    protected int getStatusCode() {
        return statusCode;
    }
    protected void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
}

The getter/setter for the int representation are protected. The public getter/setter deal with the conversion.

An alternative solution would be to use a custom type (at the cost of portability).

Related questions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!