Note that there are some explanatory texts on larger screens.

plurals
  1. POControl sort order of Hibernate EnumType.STRING properties
    primarykey
    data
    text
    <p>Currently, my project uses <code>@Enumerated(EnumType.ORDINAL)</code>, so when I sort by this column, it is ordering based on the order in the <code>enum</code>, which works fine. But I need to add some additional values to the <code>enum</code>, 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. </p> <p>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. </p> <p>So I'm thinking of switching to <code>EnumType.STRING</code> 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.</p> <p>Using the classes below, when I sort by the property "status", the results come out in this order:</p> <pre><code>hql = "from Project order by status" Development Planning Production </code></pre> <p>I'd like them to come out in this order, without using <code>EnumType.ORDINAL</code>:</p> <pre><code>Planning Development Production </code></pre> <p>Is this possible without creating a table for the <code>enum</code>, or adding an additional column to the <code>Project</code> class? I've tried this, but it throws an exception:</p> <pre><code>hql = "from Project order by status.sort" </code></pre> <p>The enum:</p> <pre><code>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; } } </code></pre> <p>The entity:</p> <pre><code>@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; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload