Enum field in JPA Entity

前端 未结 2 1817
余生分开走
余生分开走 2021-02-03 23:51

I feel a little dumb asking this but I can\'t find any simple answer to the question.

Take this simple entity as example:

@Entity
@Table( name=\"clienti\         


        
2条回答
  •  -上瘾入骨i
    2021-02-04 00:13

    public enum Gender{ 
        MALE, FEMALE 
    }
    
    
    
    @Entity
    @Table( name="clienti" )
    public class Cliente implements Serializable {
    ...
    
    // **1 case** - If database column type is number (integer) 
    // (some time for better search performance)  -> we should use 
    // EnumType.ORDINAL as @O.Badr noticed. e.g. inserted number will
    // index of constant starting from 0... in our example for MALE - 0, FEMALE - 1.
    // **Possible issue (advice)**: you have to add the new values at the end of
    // your enum, in order to keep the ordinal correct for future values.
    
    @Enumerated(EnumType.ORDINAL)
        private Gender gender;
    
    
    // **2 case** - If database column type is character (varchar) 
    // and you want to save it as String constant then ->
    
    @Enumerated(EnumType.STRING)
        private Gender gender;
    
    ...
    }
    
    // in all case on code level you will interact with defined 
    // type of Enum constant but in Database level
    

    first case (EnumType.ORDINAL)

    ╔════╦══════════════╦════════╗
    ║ ID ║    NAME      ║ GENDER ║
    ╠════╬══════════════╬════════╣
    ║  1 ║ Jeff Atwood  ║    0   ║
    ║  2 ║ Geoff Dalgas ║    0   ║
    ║  3 ║Jarrod Jesica ║    1   ║
    ║  4 ║ Joel Lucy    ║    1   ║
    ╚════╩══════════════╩════════╝
    

    second case (EnumType.STRING)

    ╔════╦══════════════╦════════╗
    ║ ID ║    NAME      ║ GENDER ║
    ╠════╬══════════════╬════════╣
    ║  1 ║ Jeff Atwood  ║  MALE  ║
    ║  2 ║ Geoff Dalgas ║  MALE  ║
    ║  3 ║Jarrod Jesica ║ FEMALE ║
    ║  4 ║ Joel Lucy    ║ FEMALE ║
    ╚════╩══════════════╩════════╝
    

提交回复
热议问题