Hibernate - how to map an EnumSet
enums, hibernate, java, orm, set
Solution
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).
Problem
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