Hibernate 中的枚举 [英] Enumerations in Hibernate
问题描述
在 DAO 中有一个字段的值来自 Java 枚举通常很有用.一个典型的例子是登录 DAO,其中通常有一个字段将用户描述为NORMAL"或ADMIN".在 Hibernate 中,我将使用以下 2 个对象以(半)类型安全的方式表示这种关系:
It is often useful to have a field in a DAO whose value comes from a Java enumeration. A typical example is a login DAO where you usually have a field that characterises the user as "NORMAL" or "ADMIN". In Hibernate, I would use the following 2 objects to represent this relationship in a (semi-)typesafe way:
class User {
String username;
String passwd;
UserType type;
}
class UserType {
private enum Type {ADMIN, NORMAL};
private String type;
//Setters/Getters for Hibernate
public void setType(String type);
public String getType();
//Setters/Getters for user
public void setUserType(UserType.Type t);
public UserType.Type getUserType();
public static UserType fromType(UserType.Type t);
}
这行得通,但我发现 UserType 类很丑,为了存储几个值需要太多的官僚作风.理想情况下,Hibernate 应该直接支持枚举字段,并会创建一个额外的表来存储枚举值.
This works, but I find the UserType class ungly and requiring too much bureaucracy just to store a couple of values. Ideally, Hibernate should support enum fields directly and would create an extra table to store the enumeration values.
我的问题是:有没有办法在Hibernate中直接映射一个枚举类?如果不是,我代表枚举的模式是否足够好或者我错过了什么?人们还使用哪些其他模式?
My question is: Is there any way to directly map an enumeration class in Hibernate? If not, is my pattern for representing enumerations good enough or am I missing something? What other patterns do people use?
推荐答案
使用 hibernate 或 JPA 注释:
using hibernate or JPA annotations:
class User {
@Enumerated(EnumType.STRING)
UserType type
}
UserType 只是一个标准的 java 5 枚举.
UserType is just a standard java 5 enum.
我无法想象这仅限于注释,但我实际上不知道如何使用 hbm 文件来做到这一点.它可能非常依赖于版本,我猜但我很确定需要 hibernate 3.2+.
I can't imagine this is just limited to just annotations but I don't actually know how to do this with hbm files. It may be very version dependant, I'm guessing but I'm pretty sure that hibernate 3.2+ is required.
在 hbm 中是可能的,但有点乱,看看这个 论坛主题
edit: it is possible in a hbm, but is a little messy, have a look at this forum thread
这篇关于Hibernate 中的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!