Can I configure Play to use mysql enums instead of

2019-02-26 17:55发布

问题:

My model contains an enum, which are mapped by JPA to an int column on my mysql database.

mysql has a native enum type, that would be more convenient to use.

How can I configure JPA to use this type?

@Entity
public class User extends Model {
  public enum Role {
    User,
    Moderator,
    Admin,
  }

  public Role role;
}

回答1:

There is no built in support for enum AFAIK, but maybe you can try this as workaround (I never test it thought):

@Entity
public class User extends Model {
    public enum Role {
        User,
        Moderator,
        Admin,
    }

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "ENUM('User', 'Moderator', 'Admin')")
    public Role role;
}

You can use EnumType.STRING which will store the value as String in the database.
But using native ENUM require you to define the columnDefinition using @Column annotation which need all your roles to be harcoded there, you see? duplication here.