Hibernate - how to create an EnumSet map

I have a color listing

public enum color { GREEN, WHITE, RED } 

and I have MyEntity that contains it.

 public class MyEntity { private Set<Color> colors; ... 

I already have a UserType to display my Enums.
Do you know how to map a transition set in Hibernate hbm.xml?
Do I need UserType or is there an easiest way?
thanks

edit:. To notice, I'm looking for hbm.xml configuration, not @CollectionOfElements Annotation

+7
java set enums orm hibernate
source share
2 answers

I am using a solution from the EnumSet mapping stream, which relies on using <element column> . You just need a table with an id and a row to map the collection ( MYENTITY_COLOR here). And the display looks like this ( EnumUserType is one of the Java 5 EnumUserType ):

 <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <typedef name="color" class="com.stackoverflow.q2402869.EnumUserType"> <param name="enumClassName">com.stackoverflow.q2402869.Color</param> </typedef> <class name="com.stackoverflow.q2402869.MyEntity" entity-name="MyEntity" table="MYENTITY"> <id name="id" type="java.lang.Long"> <column name="ID" /> <generator class="assigned" /> </id> <set name="colors" table="MYENTITY_COLORS"> <key column="ID" not-null="true"/> <element type="color" column="COLOR"/> </set> </class> </hibernate-mapping> 

The request may look like this:

 select distinct e from MyEntity e join e.colors colors where colors IN ('WHITE', 'GREEN') 

The whole solution works well for loading, saving and querying (credits for jasonab).

+7
source share

It seems you need to use the @CollectionOfElements annotation. The document is located at http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection-extratype , chapter '2.4.6.2.5. A collection of elements or compound elements. "This example also displays the Enum set.

+2
source share

All Articles