Enumerations in Hibernate

前端 未结 2 935
予麋鹿
予麋鹿 2020-12-02 06:45

It is often useful to have a field in a DAO whose value comes from a Java enumeration. A typical example is a login DAO where you usually have a field that characterises the

相关标签:
2条回答
  • 2020-12-02 07:46

    using hibernate or JPA annotations:

    class User {
       @Enumerated(EnumType.STRING)
       UserType type
    }
    

    UserType is just a standard java 5 enum.

    I can't imagine this is just limited to just annotations but I don't actually know how to do this with hbm files. It may be very version dependant, I'm guessing but I'm pretty sure that hibernate 3.2+ is required.

    edit: it is possible in a hbm, but is a little messy, have a look at this forum thread

    0 讨论(0)
  • 2020-12-02 07:48

    From the Hibernate documentation: http://www.hibernate.org/272.html

    You can create a new typedef for each of your enums and reference the typedefs in the property tag.

    Example Mapping - inline <type> tag

      <property name='suit'>
        <type name="EnumUserType">
          <param name="enumClassName">com.company.project.Suit</param>
        </type>
      </property>
    

    Example Mapping - using <typedef>

      <typedef name="suit" class='EnumUserType'>
          <param name="enumClassName">com.company.project.Suit</param>
      </typedef>
    
      <class ...>
        <property name='suit' type='suit'/>
      </class>
    
    0 讨论(0)
提交回复
热议问题