Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

java - Hibernate enum mapping

I need to map the enums which didn't implement the interface beforehand to the existing database, which stores enums in the same table as the owner class using the @Enumerated(EnumType.STRING).

class A {
    HasName name;
}

interface HasName {
    String getName();
}

enum X implements HasName {
    John, Mary;

    public String getName() { return this.name(); }
}

enum Y implements HasName {
    Tom, Ann;

    public String getName() { return this.name(); }
}

How the mapping should be handled in this case? Persisting to the database doesn't change as all of the enums implementing the interface will have different values, but I'm not sure how the objects should be retrieved from the DB (do I need a custom mapper, which will try to instantiate an enum using the specified enum classes? Does Hibernate natively support this functionality?).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Hibernate provides org.hibernate.type.EnumType to map Enumerated types. For instance,

package com.igalia.enumerates;

public enum Status {
   BUSY,
   AVAILABLE;
}

package com.igalia.entities;

class MyClass {
   private Status status;
}

Then, do your Hibernate mapping as follows:

<class name="MyClass">
   <id name="id">
      <generator class="native"/>
   </id>

   <property name="status">
      <type name="org.hibernate.type.EnumType">
         <param name="enumClass">com.igalia.enumerates.Status</param>
      </type>
   </property>
</class>

And that's it. If you prefer to use JPA annotations instead of hbm.xml, use @Enumerated(EnumType.STRING). Check it here:

Enumerations in Hibernate


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...