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)

1
  • @Enum annotation - you can specify if you want to store enum as string or as integer. Commented Feb 26, 2014 at 13:31

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

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?
I already have the database column made btw. Do I still need to specify @ColumnDef ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.