I have problems in mapping custom collection with JPA (Hiberante provider). For example when I am using object with attribute
List<Match> matches;
with
<one-to-many name="matches">
<cascade>
<cascade-all />
</cascade>
</one-to-many>
in my ORM file, it is allright; But if I replace “List matches;” by
private Matches matches;
,where “Matches” is defined like:
public class Matches extends ArrayList<Match> {
private static final long serialVersionUID = 1L;
}
It produces following error:
Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: by.sokol.labs.jpa.MatchBox.matches
Thanks for your attention!
You can, but you have to refer to it as one of the common collections –
ListorSet.so:
Why? Because Hibernate makes proxies to your collections to enable lazy loading, for example. So it creates
PersistentList,PersistentSetandPersistentBag, which areListbut aren’tMatches. So, if you want to add additional methods to that collection – well, you can’t.Check this article for more details.
You have a solution, however. Don’t use inheritance, use composition. You can, for example, add a method to your entity called
getMatchesCollection()(in addition to the traditional getter), which looks like:And your
Matchesclass would look like (using google-collections‘ForwardingList):If you can’t use google collections, simply define the
ForwardingListyourself – it’s calling all the methods of the underlyingListIf you don’t need any additional methods to operate on the structure, then don’t define a custom collection.