0

I have Enum class - Status with three values: GREEN, YELLOW, RED

I also have an entity SomeThing with a field of Status type. It has @Enumerated(EnumType.STRING) annotation.

In my DAO with Hibernate criteria I would like to sort through SomeThing items ordered by Status, but the default order by method is alphabetical (because of EnumType.STRING), so I would get GREEN items first, then RED ones and finally YELLOW ones.

But I would like to create a custom order by method. I would like to get RED items first, then GREEN, then YELLOW.

The first idea was to create a dictionary table with Status field and and int orderIndex field with OneToMany relationship (one Status type, many SomeThing records) with SomeThing entity. Then I could assign int values to different Status types and then order it by orderIndex field.

What would be the best way to achieve what I need? Thanks in advance for all your help and input.

  • you can simply order them in your getStatus method in SomeThing. order them with, e.g. like this https://stackoverflow.com/a/519844/3959856 – Jack Flamp Dec 14 '17 at 13:49
  • I see what you mean, but the issue really isn't sorting SomeThing by enum type in a custom fashion. The issue is to receive customly (?) sorted collection of SomeThings from the database.This is crucial because I am applying paging and filtering when requesting SomeThing also, so I need to receive already sorted collection, not sort it right after (because it will mess up my paging). – Dawid Nowak Dec 14 '17 at 13:56
  • my bad, I thought you wanted to sort the enums.. well, I guess, since you save status as String you can do in SQL: `FROM SomeThing s ORDER BY s.status DESC` or use Stream API method sorted. – Jack Flamp Dec 14 '17 at 14:02

0 Answers0