0

I have the following class:

@Entity
class User
{
   @Id @GeneratedValue
   private long id;

   private Language lang; //Language is an Enum of all languages

   private Role role; //Role is an enum of user roles like admin, super-admin, etc

}

My questions are:

1) How should I design the database column to work with the enum types? Should I use varchar, or any other type? (I'm using MySQL)

2) Will this class work out of the box, or do I need to do anything extra to make it work with Enums? I need to be able to both read, and write the enum values (e.g user can change his language)

Ali
  • 261,656
  • 265
  • 575
  • 769

1 Answers1

2

You can use the VARCHAR type and in the @Entity class mark the enum members with the @Enumerated and the @Column annotations (to point to which database table column will the enum member binded).

For example:

@Column(columnDefinition = "enum('BULGARIA','UNITED KINGDOM')")
@Enumerated(EnumType.STRING)
private Language lang;

@Column(columnDefinition = "enum('ADMIN','USER')")
@Enumerated(EnumType.STRING)
private Role role;
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • Will this work with existing database columns, or will it try to create them? The definition might get a bit long with all the languages, is there any other way? – Ali Feb 26 '14 at 13:52
  • I already have the database column made btw. Do I still need to specify @ColumnDef ? – Ali Feb 26 '14 at 13:55
  • Checkout this thread: http://stackoverflow.com/questions/16078681/what-properties-does-column-columndefinition-make-redundant – Konstantin Yovkov Feb 26 '14 at 14:19
  • 1
    I was able to get this to work just fine, using a varchar column and just using `@Enumerated(EnumType.STRING)`. Didn't need the `@Column` part. – Ali Feb 26 '14 at 16:07