JPA实体中的枚举字段 [英] Enum field in JPA Entity
问题描述
问这个问题我有点傻,但是我找不到这个问题的简单答案.
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" )
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;
//...
}
它代表一个人,所以我想添加一个"性别"属性.
It represents a person, so I want to add a "gender" property.
它将是男性"或女性".那又怎样呢?
It will be "male" or "female". So what?
我可以使用字符串,并记住"m"代表男性,"f"代表女性.
I can use a String, and keep in mind that "m" stands for male and "f" for female.
或者我可以使用布尔值"isMale"(是或否).
Or I can use a boolean "isMale", true or false.
但是,无论哪种情况,我都不认为Hibernate的纯粹主义者会很高兴:)
However, I don't think in either case Hibernate purists would be happy :)
谷歌搜索一点,我发现最佳实践是使用枚举.
Googling a little bit I found that the best practice is using an enum.
我对如何使用它有些困惑.你能帮我举个例子吗?
I am a little confused on how to use it. Can you help me with an example?
推荐答案
您可以将enum
映射到String
或序数.映射到String
是更可移植的方法,因为映射将在更改枚举顺序后仍然存在.
You can map your enum
to a String
or to an ordinal number. Mapping to String
is the more portable approach as the mapping will survive changing the enumeration order.
使用您的示例:
@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {
...
@Enumerated(EnumType.STRING)
private Gender gender;
...
}
字符串映射将使用枚举类型的简单名称,因此数据库中将有两个可能的值-'Male'和'Female'
The string mapping will use the simple name of the enumeration type, so you would have two possible values in the DB - 'Male' and 'Female'
public enum Gender { MALE, FEMALE }
持久性提供程序负责映射,因此在您的代码中,您可以继续使用Gender
枚举,而不必担心字符串或序数.
The persistence provider takes care of the mapping, so in your code, you can continue using the Gender
enum and not worry about Strings or ordinals.
这篇关于JPA实体中的枚举字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!