JPA实体中的枚举字段

Fab*_* B. 23 enums hibernate jpa

我觉得有点愚蠢,但我找不到任何简单的答案.

以这个简单的实体为例:

@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    private String nome;

    private String cognome;

//...
}
Run Code Online (Sandbox Code Playgroud)

它代表一个人,所以我想添加一个" 性别 "属性.

它将是"男性"或"女性".所以呢?

我可以使用一个字符串,并记住"m"代表男性,"f"代表女性.

或者我可以使用布尔值"isMale",true或false.

但是,我不认为在任何一种情况下Hibernate纯粹主义者会很高兴:)

谷歌搜索了一下我发现最好的做法是使用枚举.

我对如何使用它有点困惑.你能帮我举个例子吗?

kos*_*tja 44

您可以将您的地图映射enum到a String或序号.映射到String更便携的方法,因为映射将在更改枚举顺序后继续存在.

使用你的例子:

@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {

...
    @Enumerated(EnumType.STRING)
    private Gender gender;
...
}
Run Code Online (Sandbox Code Playgroud)

字符串映射将使用枚举类型的简单名称,因此您在DB中将有两个可能的值 - "男性"和"女性"

public enum Gender { MALE, FEMALE }
Run Code Online (Sandbox Code Playgroud)

持久性提供程序负责映射,因此在代码中,您可以继续使用Gender枚举,而不必担心字符串或序数.


Mus*_*usa 6

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
Run Code Online (Sandbox Code Playgroud)

第一种情况(EnumType.ORDINAL)

??????????????????????????????
? ID ?    NAME      ? GENDER ?
??????????????????????????????
?  1 ? Jeff Atwood  ?    0   ?
?  2 ? Geoff Dalgas ?    0   ?
?  3 ?Jarrod Jesica ?    1   ?
?  4 ? Joel Lucy    ?    1   ?
??????????????????????????????
Run Code Online (Sandbox Code Playgroud)

第二种情况(EnumType.STRING)

??????????????????????????????
? ID ?    NAME      ? GENDER ?
??????????????????????????????
?  1 ? Jeff Atwood  ?  MALE  ?
?  2 ? Geoff Dalgas ?  MALE  ?
?  3 ?Jarrod Jesica ? FEMALE ?
?  4 ? Joel Lucy    ? FEMALE ?
??????????????????????????????
Run Code Online (Sandbox Code Playgroud)

  • 如果你选择字符串类型并希望输出小写,可以实现吗?如何使用@Enumerated(EnumType.STRING)? (2认同)