tags:

views:

2775

answers:

3

Is there a way in JPA to map a collection of Enums within the Entity class? Or the only solution is to wrap Enum with another domain class and use it to map the collection?

@Entity
public class Person {
    public enum InterestsEnum {Books, Sport, etc...  }
    //@???
    Collection<InterestsEnum> interests;
}

I am using Hibernate JPA implementation, but of course would prefer implementation agnostic solution.

+4  A: 

Collections in JPA refer to one-to-many or many-to-many relationships and they can only contain other entities. Sorry, but you'd need to wrap those enums in an entity. If you think about it, you'd need some sort of ID field and foreign key to store this information anyway. That is unless you do something crazy like store a comma-separated list in a String (don't do this!).

cletus
+3  A: 

using Hibernate you can do

@CollectionOfElements(targetElement = InterestsEnum.class)
@JoinTable(name = "tblInterests", joinColumns = @JoinColumn(name = "personID"))
@Column(name = "interest", nullable = false)
@Enumerated(EnumType.STRING)
Collection<InterestsEnum> interests;
In case anybody reads this now ... @CollectionOfElements is now deprecated, instead use: @ElementCollection
+1  A: 

JPA2 allows Collection of non-Entity objects, see http://www.datanucleus.org/products/accessplatform_1_1/jpa/orm/one_to_many_collection.html#join_nonpc

--Andy DataNucleus

DataNucleus