6

I am using JPA 2.1. I want to genrate mysql enum type column like: gender enum('male','female'). My Enum class is

public enum Gender {
  MALE,
  FEMALE
}

In JPA entity class

@Enumerated
private Gender gender;//generate int type column

And

@Enumerated(EnumType.STRING)
private Gender gender; //generate varchar type column. 

Is there any way to generate enum type column in MySql?

Masudul
  • 21,823
  • 5
  • 43
  • 58

2 Answers2

9

Use following code:

public enum Gender {
    MALE, FEMALE;
}

@Enumerated(EnumType.STRING)
@Column(columnDefinition = "ENUM('User', 'Moderator', 'Admin')")
public Role role;
}
  • 1
    Not only does this not compile, but also it mixes up `Gender` and `Role` and therefore doesn't answer the question, nor explain anything. Why would people upvote this? – Michel Jung Mar 07 '17 at 22:55
  • While the example is put together negligently, this is the only answer I was able to find that shows how to map an enum to an actual SQL ENUM type with JPA, as opposed to just storing your enum values in an unsafe number or string type. – UncleBob Nov 15 '17 at 13:26
  • Is enum type ANSI compatible? Is enum defined in standard SQL or it's just for MySQL? In that case: isn't this solution coupling the `@Entity` class (I asume `Person` or something alike) with the DB table (and the DBMS)? – Alvaro Pedraza Mar 02 '18 at 03:04
-1

If you would like to use string enumeration value in database, the column type must be varchar base on database sever. Actually, I am not clear I want to genrate mysql enum type column. But, if u would like to display the output MALE to male, reference as below :

public enum Gender {
    FEMALE("female"), MALE("male");

    private String label;

    private Gender(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

test calss

public static void main(String args[]) {
    System.out.println(Gender.MALE)
}

Output : male

Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131