AnnotationException:针对未映射的 class 使用 @OneToMany 或 @ManyToMany:

AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:

我有一个枚举如下:

public enum UserRole {
    ADMIN,ORGANIZER,USER
}

然后在另一个 class 中,我试图收集这个枚举:

@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]

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

您必须使用@ElementCollection,因为此用户角色是枚举且未包含在数据库中。 JPA 2.0 使用 @ElementCollection:

使后一种情况变得简单

JPA 2.0 defines an ElementCollection mapping. It is meant to handle several non-standard relationship mappings. An ElementCollection can be used to define a one-to-many relationship to an Embeddable object, or a Basic value (such as a collection of Strings). An ElementCollection can also be used in combination with a Map to define relationships where the key can be any type of object, and the value is an Embeddable object or a Basic value.

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