Enum in Hibernate, persisting as an enum

后端 未结 5 1877
梦如初夏
梦如初夏 2020-11-29 05:07

In my MySQL database, there\'s the column \"gender enum(\'male\',\'female\')\"

I\'ve created my enum \"com.mydomain.myapp.enums.Gender\", and in my Person

相关标签:
5条回答
  • 2020-11-29 05:35

    If you give Hibernate a column definition, it won't try to guess one:

    @Column(columnDefinition = "enum('MALE','FEMALE')")
    @Enumerated(EnumType.STRING)
    private Gender gender;
    

    If you aren't relying on Hibernate to generate your schema for any reason, you don't even have to provide real values for the columnDefinition. This way, you remove an instance where you need to keep the values in sync. Just keep your Java enum and your Liquibase or SQL script in sync:

    @Column(columnDefinition = "enum('DUMMY')")
    @Enumerated(EnumType.STRING)
    private ManyValuedEnum manyValuedEnum;
    
    0 讨论(0)
  • 2020-11-29 05:37

    Try to use @Enumerated(EnumType.STRING) and define your enum like this

    enum Gender {
      male,
      female
    }
    

    Note lower case values.

    This will work at least with VARCHAR columns. It will store enum as string 'male' or 'female'.

    0 讨论(0)
  • 2020-11-29 05:45

    not sure why it is not in Hibernate documentation but you can do this

    <property name="type" column="type" not-null="true">
        <type name="org.hibernate.type.EnumType">
            <param name="enumClass">com.a.b.MyEnum</param>
            <param name="type">12</param>
            <!-- 12 is java.sql.Types.VARCHAR -->
        </type> 
    </property>
    
    0 讨论(0)
  • 2020-11-29 05:52

    My understanding is that MySQL enum type is very proprietary and not well supported by Hibernate, see this comment from Gavin King (this related issue is a bit different but that's not the important part).

    So, I actually think that you'll have to use your own UsereType and I'd recommend to use the Flexible solution - working version from the Java 5 EnumUserType (see Appfuse's Java 5 Enums Persistence with Hibernate for an example).

    Personally, I'd just forget the idea to use MySQL enum, I'm not convinced that the "benefits" are worth it (see this answer for more details).

    0 讨论(0)
  • 2020-11-29 05:53

    Not for this case but if someone is using XML mapping:

    <property name="state" column="state" not-null="true">
      <type name="org.hibernate.type.EnumType">
        <param name="enumClass">com.myorg.persistence.data.State</param>
      </type>
    </property>
    

    The database column type must be numeric e.g. tinyint on a mysql to make reading ordinal values possible.

    0 讨论(0)
提交回复
热议问题