In hibernate, is it possible to define a mapping for a class to a set of enums?
I\'ve been able to find examples of how to define mappings of Sets and I\'ve been a
Does this not do what you need?
To elaborate on the flippant initial response, the reference provides a means to use the ordinal of the enum to map enumerations.
In this case it's actually simpler than it looks, because you are hosting the enums in a set, you need to provide an accessor for the WicketType to the sub-type of IntEnumUserType, the super-type will take care of mapping the ordinal to the instance.
package test;
public class WicketTypeState extends IntEnumUserType<WicketType> {
private WicketType wicketType;
public WicketTypeState() {
// we must give the values of the enum to the parent.
super(WicketType.class, WicketType.values());
}
public WicketType getWicketType() {
return wicketType;
}
public void setWicketType(final WicketType wicketType) {
this.wicketType = wicketType;
}
}
Define the mappings for the enum table:
<hibernate-mapping package="test">
<class name="Wicket" table="Wicket">
<id name="id" column="ID"/>
<set name="wicketTypes" table="WicketType" inverse="true">
<key column="ID"/>
<one-to-many class="test.WicketTypeState"/>
</set>
</class>
</hibernate-mapping>
Then for the type with the set of enums, define a set mapping for that property:
<hibernate-mapping package="test">
<class name="WicketTypeState" lazy="true" table="WicketType">
<id name="WicketType"
type="test.WicketTypeState"/>
</class>
</hibernate-mapping>
This worked on my box(tm), let me know if you need any more info.
The sample code below shows how what you want can be achieved with annotations.
@Entity
@Table (name = "wicket")
public class Wicket {
...
...
private List<WicketType> wicketTypes = new ArrayList<WicketType>();
@CollectionOfElements(fetch=FetchType.EAGER)
@JoinTable(
name="wicket_wicket_types", // ref table.
joinColumns = {@JoinColumn(name="wicket_id")}
)
@Column(name="wicket_type_id")
public List<WicketType> getWicketTypes() {
return this.wicketTypes;
}
public void setWicketTypes(List<WicketType> wicketTypes) {
this.wicketTypes = wicketTypes;
}
...
...
}
WicketType
is a standard Java 5 Enum whose order and ordinals of enum declarations match order and the column (wicket_type_id
) values in the wicket_type
table.
public enum WicketType {
WICKET_TYPE1, WICKET_TYPE2 ...
}
A simpler way is
<typedef name="WicketTypeType" class="org.hibernate.type.EnumType">
<param name="enumClass">Wicket</param>
<param name="type">12</param>
</typedef>
<class name="Wicket"...
<set name="WicketType" table="Ref Table">
<key column="W_ID" />
<element column="W_TypeID" type="WicketTypeType"/>
</set>
...
</class>