28

我觉得问这个有点愚蠢,但我找不到任何简单的答案。

以这个简单的实体为例:

@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;

//...
}

它代表一个人,所以我想添加一个“性别”属性。

它将是“男性”或“女性”。所以呢?

我可以使用字符串,并记住“m”代表男性,“f”代表女性。

或者我可以使用布尔值“isMale”,真或假。

但是,我认为无论哪种情况,Hibernate 纯粹主义者都不会高兴:)

谷歌搜索了一下,我发现最好的做法是使用enum

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

4

2 回答 2

50

您可以将您的映射enum到 aString或序数。映射到String是更便携的方法,因为映射将在更改枚举顺序后继续存在。

使用您的示例:

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

...
    @Enumerated(EnumType.STRING)
    private Gender gender;
...
}

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

public enum Gender { MALE, FEMALE }

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

于 2013-01-21T12:43:59.853 回答
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

第一种情况(EnumType.ORDINAL)

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

第二种情况(EnumType.STRING)

╔════╦══════════════╦════════╗
║ ID ║    NAME      ║ GENDER ║
╠════╬══════════════╬════════╣
║  1 ║ Jeff Atwood  ║  MALE  ║
║  2 ║ Geoff Dalgas ║  MALE  ║
║  3 ║Jarrod Jesica ║ FEMALE ║
║  4 ║ Joel Lucy    ║ FEMALE ║
╚════╩══════════════╩════════╝
于 2018-02-03T08:39:24.870 回答