Currently, my project uses @Enumerated(EnumType.ORDINAL)
, so when I sort by this column, it is ordering based on the order in the enum
, which works fine. But I need to add some additional values to the enum
, which need to be inserted at different locations in the list of enum values and can't be just added to the bottom to maintain the correct sort order.
If I do this, my database will be messed up. I'll have to write some scripts to translate all these ordinal values to the correct new ordinal. There is a possibility that more status will have to be added later. Since I have to fix all the data in the database, I'd like to only have to do it once, as it will be a big task.
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.
Using the classes below, when I sort by the property "status", the results come out in this order:
hql = "from Project order by status"
Development
Planning
Production
I'd like them to come out in this order, without using EnumType.ORDINAL
:
Planning
Development
Production
Is this possible without creating a table for the enum
, or adding an additional column to the Project
class? I've tried this, but it throws an exception:
hql = "from Project order by status.sort"
The enum:
public enum Status {
PLANNING("Planning", 0),
DEVELOPMENT("Development", 1),
PRODUCTION("Production", 2);
private final String name;
private final int sort;
private Status(String name, int sort) {
this.name = name;
this.sort = sort;
}
@Override
public String toString() {
return name;
}
}
The entity:
@Entity
public class Project {
private Long id;
private Status status;
@Id
@GeneratedValue
public Long getId() {
return this.id;
}
private void setId(Long id) {
this.id = id;
}
@Enumerated(EnumType.STRING)
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}