Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“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);     } } 
like image 485
mh123hack Avatar asked May 30 '17 09:05

mh123hack


2 Answers

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>(); 
like image 176
cнŝdk Avatar answered Oct 18 '22 21:10

cнŝdk


You should map to interfaces and not implementations. This:

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

Should be (also replaced the TreeSet because a HashSet is enough here):

@OneToMany(cascade=CascadeType.ALL, targetEntity=CoachGroup.class) @JoinColumn(name="id") private Set<CoachGroup> coachGroups = new HashSet<>(); 
like image 30
Nyamiou The Galeanthrope Avatar answered Oct 18 '22 21:10

Nyamiou The Galeanthrope