Issue
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|
....
Solution
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.
Answered By - ChssPly76
Answer Checked By - Katrina (JavaFixing Volunteer)