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

标签 java hibernate exception collections hibernate-mapping

早上好 Stackoverflow,

我的问题是它给了我错误:

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

你知道为什么吗?

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

最佳答案

异常很简单,说:非法尝试将非集合映射为@OneToMany、@ManyToMany 或@CollectionOfElements,所以原因在这里很明显,如果我们看看 Hibernate Collection mapping documentation它明确指出:

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...

您使用了 TreeSet,它是 Set<E>SortedSet<E> 接口(interface)的实现。因此,您的实际映射不适用于 TreeSet ,您应该使用 Set<CoachGroup> 而不是 TreeSet<CoachGroup> :

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

关于java - “Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258541/

相关文章:

java - 为什么未登录异常堆栈跟踪?

java - 尝试访问注入(inject)的 Bean 时出现空指针异常

java - 记录直接从数据库中获取,而不是从缓存文件中获取

Hibernate/JPA 2.0 @OneToOne 关系与可能不存在的匹配行

Hibernate:检查对象是否存在

Python:为每个引发的异常做一些事情

spring - 未调用 ResponseEntityExceptionHandler 的重写 handleMethodArgumentNotValid 方法

java - while (rs.next()) 没有返回所有结果?

java - 仅使用一种颜色生成渐变

java - 如何在 Android 应用程序中通过网络对用户进行身份验证,而不在本地设备上复制数据?