views:

448

answers:

2

Hi all,
I've a Color Enum

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 map my Enums.
Do you know how to map a Set of Enums in the Hibernate hbm.xml?
Do I need a UserType or there's an easiest way?
Thanks

edit: Just to remark, I'm looking for the hbm.xml configuration not the @CollectionOfElements Annotation

+1  A: 

It seems you need to use the @CollectionOfElements annotation. The doc is at http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection-extratype, chapter '2.4.6.2.5. Collection of element or composite elements'. The example also maps a Set of Enum.

FelixM
Thanks for your response. Actually I'm using XML to map my java classes and I'm wondering if there is an easy way to achieve the same
al nik
+3  A: 

I use the solution from the EnumSet mapping thread which relies on the use of <element column>. You just need a table with an id and a string to map the collection (MYENTITY_COLOR here). And the mapping looks like that (the EnumUserType is the one from 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"&gt;
<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>

Query might look like this:

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

The whole solution works well for loads, saves and queries (credits to jasonab).

Pascal Thivent
thanks a lot.. it wasn't easy to find a solution online
al nik