【问题标题】:AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:AnnotationException:使用@OneToMany 或@ManyToMany 定位未映射的类:
【发布时间】:2017-11-21 12:32:46
【问题描述】:

我有一个枚举如下:

public enum UserRole {
    ADMIN,ORGANIZER,USER
}

然后在另一个班级,我正在尝试收集这个枚举:

@Data
@Entity
public class User {

    @Id
    @GeneratedValue
    Long id;

    @OneToMany
    Collection<UserRole> userRole;

}

但它抱怨以下错误:

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.eventer.demo.model.User.userRole[com.eventer.demo.model.UserRole]

【问题讨论】:

    标签: java hibernate spring-boot enums javabeans


    【解决方案1】:

    你不能在非实体类上使用@OneToMany。您应该改用 @ElementCollection,它可以用于 String、Integer、Enum 和其他没有主键的基本类型。

    【讨论】:

      【解决方案2】:

      您必须使用@ElementCollection,因为,此用户角色是枚举并且它不包含在数据库中。 JPA 2.0 使用 @ElementCollection 使后一种情况变得简单:

      JPA 2.0 定义了一个 ElementCollection 映射。它旨在处理 几个非标准的关系映射。 ElementCollection 可以 用于定义与 Embeddable 对象的一对多关系, 或基本值(例如字符串集合)。一个 ElementCollection 也可以与 Map 结合使用来定义 键可以是任何类型的对象的关系,而值 是 Embeddable 对象或 Basic 值。

          @ElementCollection(targetClass=UserRole.class)
          @Enumerated(EnumType.STRING)
          @CollectionTable(name = "USER_ROLE",
          joinColumns = @JoinColumn(name = "USER_ID"))
          @Column(name="ROLE")
          Collection<UserRole> roles;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-15
        • 2011-06-24
        • 2016-08-25
        相关资源
        最近更新 更多