2

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;
}
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 2
    Duplicate of : http://stackoverflow.com/questions/2160700/enum-in-hibernate-persisting-as-an-enum and in short: DO NOT USE MYSQL ENUM! There are nicer patterns, using ORDINAL for compactness and STRING for readability. You can make an enum with a short string for the database, and a longer one for your code. – Stefano Jan 03 '12 at 11:24
  • 1
    @Stefano - not really a duplicate because of the context of Play Framework. But anyway, I didn't really know whether enum is proprietary mysql or not. I wouldn't want to change my code just to support a proprietary mysql behavior, so I probably will be sticking to Play defaults. – ripper234 Jan 03 '12 at 11:37
  • 2
    looks like i'm reading all of your play! questions now :D ; I would say in this case it does not make any difference whether you're going through Play! or not, because Play! just extends JPA/Hibernate so every problem there will be an issue with Play! too! – Stefano Jan 03 '12 at 11:48
  • @Stefano - I tend to ask a lot of questions (that's how I got most of my Stack Overflow rep). I accepted the answer, not sure if it's an _exact_ dup or not, because of the context that I intended (even if they turned out to have the same answer). – ripper234 Jan 03 '12 at 11:53

1 Answers1

8

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.

sverdianto
  • 136
  • 3