Search code examples
javahibernatejpamany-to-many

Which collections are supported by Hibernate @ManyToMany annotation


I used @ManyToMany annotation on a Set and it worked fine.

@ManyToMany
@JoinTable(name="stud_course_map",joinColumns={@JoinColumn(name="stud_id ")}, inverseJoinColumns={@JoinColumn(name="course_id")} )
public Set<Course> getEnrolledCourses() {
    return enrolledCourses;
}

When I used ArrayList instead of Set it throws exception:

org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: com.kaushik.winnersoft.data.Student.enrolledCourses

Is ArrayList not supported? Which all collection are supported by @ManyToMany annotation?


Solution

  • The supported interfaces are:

    java.util.Set
    java.util.List
    java.util.Collection
    

    You get the exception because you have used a concrete implementation of one of those interfaces. Always define the @ManyToMany or @OneToMany using an interface as given above and you will be fine.