Skip to content
Advertisement

“Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements”

Good morning Stackoverflow,

I have the problem that it gives me the error:

Failed to create sessionFactory object.org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: nl.scalda.pasimo.model.employeemanagement.EducationTeam.coachGroups

Do you know why?

@OneToMany(cascade=CascadeType.ALL, targetEntity=CoachGroup.class)
@JoinColumn(name="id")
private TreeSet<CoachGroup> coachGroups = new TreeSet<>();
private SessionFactory factory;

private void initialiseFactory() {
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

Advertisement

Answer

The Exception is straightforward and says : Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements, so the cause is obvious here and if we take a look at the Hibernate Collection mapping documentation it clearly states that:

As a requirement persistent collection-valued fields must be declared as an interface type (see Example 7.2, “Collection mapping using @OneToMany and @JoinColumn”). The actual interface might be java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap

And you used TreeSet which is an implementation class for both Set<E> and SortedSet<E> interfaces. So your actual mapping won’t work with TreeSet, you should use a Set<CoachGroup> instead of a TreeSet<CoachGroup>:

private Set<CoachGroup> coachGroups = new HashSet<CoachGroup>();
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement