Hibernate 中的枚举
在 DAO 中拥有一个其值来自 Java 枚举的字段通常很有用。 一个典型的示例是登录 DAO,其中通常有一个将用户特征描述为“NORMAL”或“ADMIN”的字段。 在 Hibernate 中,我将使用以下 2 个对象以(半)类型安全的方式表示这种关系:
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 应该直接支持枚举字段,并创建一个额外的表来存储枚举值。
我的问题是:有没有办法在Hibernate中直接映射枚举类? 如果没有,我表示枚举的模式是否足够好,还是我遗漏了一些东西? 人们还使用哪些其他模式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 hibernate 或 JPA 注释:
UserType 只是一个标准的 java 5 枚举。
我无法想象这仅限于注释,但我实际上不知道如何使用 hbm 文件来做到这一点。 我猜它可能非常依赖于版本,但我很确定需要 hibernate 3.2+。
编辑:在 hbm 中是可能的,但有点混乱,看看这个 论坛线程
using hibernate or JPA annotations:
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 文档: http://www.hibernate.org/272.html
您可以为每个枚举创建一个新的 typedef 并在属性标记中引用 typedef。
示例映射 - 内联
标记示例映射 - 使用
From the Hibernate documentation: http://www.hibernate.org/272.html
You can create a new typedef for each of your enums and reference the typedefs in the property tag.
Example Mapping - inline
<type>
tagExample Mapping - using
<typedef>