Filling a database table with enumeration values ​​in sleep mode

is it possible to let Hibernate (3.6) populate the database table with the values ​​for this listing? 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 enumeration without any problems from another entity class using

 @Enumerated(EnumType.STRING) public Role getRole() 

My question is: how can I automatically populate the appropriate ROLE table? All basic logic and definitions are in the XML specification. Of course, I can generate a sql file from this XSL specification and let Hibernate import it with import.sql sematic at startup ... But is there a more elegant way?

The table should look like this:

 |RoleID|RoleName | | 0 |ROLE_USER_FREE| .... 
+4
source share
2 answers

You need to choose a side - either you are going to use Role as an enumeration, or as an entity. You are trying to do both, and this will only lead to trouble on the road.

If you want to use an enumeration

  • Remove @Entity annotation from Role . This is not an entity; it does not have a primary key. Nor should it be volatile, so little is needed to preserve it.
  • Delete the Roles table (or something else called) from the database. Hibernate stores names by name (if you use @Enumerated(EnumType.STRING) or by index in the values() array (if you use @Enumerated(EnumType.ORDINAL) annotation). In any case, it will never reference your additional table. When matching with you ( @Enumerated(EnumType.STRING) ) it @Enumerated(EnumType.STRING) no sense to start with RoleID .

If you want to use an entity

  • Make Role true entity - POJO with getters / setters and an identifier. It may or may not change depending on what you want.
  • Match it to the Roles table.
  • Name it as @ManyToOne from other tables.
  • You will need to fill out the table yourself; There is no built-in way for Hibernate to do this for you.
+6
source

It fills my database perfectly

 public class Person implements UserAccount { public static enum Role { anon(6), admin(1), standard(4), manager(3), user(5), director(2); private int weight; Role(int weight) { this.weight = weight; } public int weight() { return weight; } } @ElementCollection(targetClass = Role.class, fetch=FetchType.EAGER) @Enumerated(EnumType.STRING) // Possibly optional (I'm not sure) but defaults to ORDINAL. @CollectionTable(name="person_roles") @Column(name="role") public Set<Role> getRoles() { return roles; } ... 
+4
source

Source: https://habr.com/ru/post/1347569/


All Articles