Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - how to map an EnumSet

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

like image 988
mickthompson Avatar asked Mar 08 '10 16:03

mickthompson


1 Answers

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">
<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).

like image 82
Pascal Thivent Avatar answered Oct 19 '22 21:10

Pascal Thivent