使用hibernate中的枚举值填充数据库表 [英] Populate database table with enum values in hibernate
问题描述
有没有可能让Hibernate(3.6)用给定枚举的值填充数据库表?
我有以下类:
@Entity
public enum角色
{
ROLE_USER_FREE(ROLE_USER_FREE),
ROLE_USER_STANDARD(ROLE_USER_STANDARD),
ROLE_USER_PREMIUM(ROLE_USER_PREMIUM),
ROLE_ADMIN(ROLE_ADMIN);
...构造函数/ setter / getter等
}
我可以使用这个枚举没有来自另一个实体类的任何问题使用
@Enumerated(EnumType.STRING)
public Role getRole )
我的问题是,如何自动填充相应的表ROLE?
所有基础逻辑和定义都在XML规范中。当然,我可以通过XSL从这个规范生成一个sql文件,并让Hibernate在启动时通过import.sql sematic导入这个文件...但是还有更多优雅的方式吗?
表应该如下所示:
| RoleID | RoleName |
| 0 | ROLE_USER_FREE |
....
选择一个方面 - 要么使用 Role
作为枚举或实体。你试图做到这一点,这只会导致沿途的麻烦。
如果你想使用枚举
- 从
角色删除
@Entity
注释>。它不是一个实体,它没有主键。它也不应该是可变的,所以在坚持它是没有意义的。 - 删除
角色
数据库。 Hibernate通过名称持久化枚举(如果您使用@Enumerated(EnumType.STRING)
映射)或通过values()中的索引
数组(如果您使用@Enumerated(EnumType.ORDINAL)
注释)。无论哪种方式,它将永远不会引用您的附加表。通过映射(@Enumerated(EnumType.STRING)
),RoleID
开始时没有意义。
如果您想使用实体
角色
一个真正的实体 - 带有getters / setters和标识符的POJO。
@ManyToOne
来自其他表格。
is there any possibility to let Hibernate (3.6) populate a database table with values for a given enum ? I have the following class:
@Entity
public enum Role
{
ROLE_USER_FREE("ROLE_USER_FREE"),
ROLE_USER_STANDARD("ROLE_USER_STANDARD"),
ROLE_USER_PREMIUM("ROLE_USER_PREMIUM"),
ROLE_ADMIN("ROLE_ADMIN");
... constructor / setter / getter etc.
}
I can use this enum without any problems from another entity class using
@Enumerated(EnumType.STRING)
public Role getRole()
My question is, how can I populate the corresponding table ROLE automatically ? All the underlying logic and definiations resides in an XML specification. Of course, I can generate a sql file from this spec by XSL and let Hibernate import this by the import.sql sematic at startup... But is there a more elegant way ?
The table should look like this:
|RoleID|RoleName |
| 0 |ROLE_USER_FREE|
....
You have to pick a side - either you're going to use Role
as enum or as entity. You're trying to do both and that's only going to lead to trouble along the road.
If you want to use enum
- Remove
@Entity
annotation fromRole
. It's not an entity, it doesn't have a primary key. It also shouldn't be mutable, so there's little point in persisting it. - Remove
Roles
(or whatever it's called) table from the database. Hibernate persists enums by name (if you're using@Enumerated(EnumType.STRING)
mapping) or by index invalues()
array (if you're using@Enumerated(EnumType.ORDINAL)
annotation). Either way, it will never reference your additional table. With you mapping (@Enumerated(EnumType.STRING)
) it's pointless to haveRoleID
to begin with.
If you want to use an entity
- Make
Role
a true entity - POJO with getters / setters and identifier. It may or may not be mutable depending on what you want. - Map it to your 'Roles' table.
- Reference it as
@ManyToOne
from your other tables. - You will have to populate the table yourself; there's no built-in way for Hibernate to do it for you.
这篇关于使用hibernate中的枚举值填充数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!