在Hibernate中枚举 [英] Enumerations in Hibernate
问题描述
DAO中有一个字段通常很有用,它的值来自Java枚举。一个典型的例子是登录DAO,其中通常有一个字段将用户表征为NORMAL或ADMIN。在Hibernate中,我将使用以下两个对象以(半)类型安全的方式表示这种关系:
class User {
字符串用户名;
字符串密码;
UserType类型;
}
class UserType {
private enum类型{ADMIN,NORMAL};
私有字符串类型;
// Setter / 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应直接支持enum字段,并创建一个额外的表来存储枚举值。
我的问题是:有没有什么办法直接映射枚举类休眠?如果没有,我的模式代表枚举是否足够好,或者我错过了什么?人们使用什么其他模式?
使用hibernate或JPA注解:$ b
code> class User {
@Enumerated(EnumType.STRING)
UserType type
}
UserType只是一个标准的java 5枚举。
我无法想象这仅仅局限于注释,但实际上我不知道如何用hbm文件来做到这一点。它可能是非常依赖版本,我猜,但我非常确定,需要休眠3.2+。
编辑:它可能在hbm,但是有点混乱,看看这个论坛主题
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);
}
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.
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?
using hibernate or JPA annotations:
class User {
@Enumerated(EnumType.STRING)
UserType type
}
UserType is just a standard java 5 enum.
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.
edit: it is possible in a hbm, but is a little messy, have a look at this forum thread
这篇关于在Hibernate中枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!