如何使用@OneToMany和@ManyToOne嵌套?

时间:2016-02-12 14:41:21

标签: hibernate jpa one-to-many many-to-one

我有三个实体如下:

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"id", "bricksets", "themes"})
@Entity
public class Brand {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;                // Unique database primary key

    @OneToMany(mappedBy = "brand", cascade = CascadeType.ALL)
    private List<Brickset> bricksets;

    @OneToMany(mappedBy = "brand", cascade = CascadeType.ALL)
    private List<Theme> themes;

    @NotNull
    private String name;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"id"})
@ToString(exclude={"brand", "theme"})
@Entity
public class Brickset {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;            // Unique database primary key

    @NotNull
    private String number;      // set number

    @ManyToOne
    @JoinColumn(name = "brand_id")
    private Brand brand;

    @ManyToOne
    @JoinColumn(name = "theme_id")
    private Theme theme;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"id"})
@ToString(exclude={"brand", "brickset"})
@Entity
public class Theme {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;                // Unique database primary key

    @NotNull
    private String name;

    @ManyToOne
    @JoinColumn(name = "brand_id")
    private Brand brand;

    @OneToMany(mappedBy = "Theme", cascade = CascadeType.ALL)
    private List<Brickset> brickset;
}

但是我遇到了如下编译错误,我试图自己解决它,但我是JPA / Hibernate的新手,你能帮助我,我该怎么办?我认为问题是我在实体主题中使用了ManyToOne和OneToMany,可能会被JPA / Hibernate搞糊涂,我可能有意义吗?

Caused by: org.hibernate.AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: com.zangland.entity.Theme.brickset

1 个答案:

答案 0 :(得分:1)

您需要使用集合来java.util.Set注释。

Hibernate要求将持久的集合值字段声明为接口类型。

实际界面可能是java.util.Collectionjava.util.Listjava.util.Mapjava.util.SortedSetjava.util.SortedMaporg.hibernate.usertype.UserCollectionType或您喜欢的任何内容(&# 34;你喜欢的任何东西&#34;意味着你必须编写@OneToMany(mappedBy = "theme", cascade = CascadeType.ALL) private Set<Brickset> brickset; 的实现。)

{{1}}