Custom sort order for enumeration field

Is it possible to change alphabetical sorting in JPA for self-determination?

I have this data in a column division:

BRONZE
SILVER
GOLD
DIAMOND

And I matched this with the entity field:

public enum Division {
    BRONZE,
    SILVER,
    GOLD,
    DIAMOND
}

@Entity
public class MyEntity {

  @Enumerated(EnumType.STRING)
  private Division division;

  ...
}

If I use the default sort, I get the alphabetical order:

  • In RONZE
  • D iamond
  • G OLD
  • S ilver

But I want to sort by ore quality (in order of listing).

+4
source share
2 answers

( ) . , Comparator - . -, .

. , - :

@Enumerated(EnumType.ORDINAL) // The default
private Division division;

, enum Entity . , .

- Formula ( ):

@Enumerated(EnumType.STRING)
private Division division;

@Formula("case division when 'BRONZE' then 0 when 'SILVER' then 1 ... end")
private int divisionQuality;

- .

+3
0

Source: https://habr.com/ru/post/1614344/


All Articles