“非法尝试将非收藏夹映射为@OneToMany、@ManyToMany或@CollectionOfElements”

早上好,Stackoverflow,

我有一个问题,它给了我错误:

未能创建 sessionFactory object.org.hibernate.AnnotationException:非法尝试将非集合映射为@OneToMany、@ManyToMany或@CollectionOfElements:nl.scalda.pasimo.model.employeemanagement.EducationTeam.coachGroups

你知道为什么吗?

@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);
    }
}

答案 1

例外很简单,并说:非法尝试将非集合映射为@OneToMany,@ManyToMany或@CollectionOfElements,因此原因在这里很明显,如果我们看一下Hibernate集合映射文档,它清楚地表明:

作为要求,必须将持久集合值字段声明为接口类型(请参见例 7.2 “使用@OneToMany和@JoinColumn的集合映射”)。实际的接口可能是 、 、 、 、 ...java.util.Setjava.util.Collectionjava.util.Listjava.util.Mapjava.util.SortedSetjava.util.SortedMap

你使用了 TreeSet,它是两者和接口的实现。所以你的实际映射将不起作用,你应该使用 a 而不是 :Set<E>SortedSet<E>TreeSetSet<CoachGroup>TreeSet<CoachGroup>

private Set<CoachGroup> coachGroups = new HashSet<CoachGroup>();

答案 2

您应该映射到接口而不是实现。这:

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

应该是(也替换了树集,因为哈希集在这里就足够了):

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