非法尝试将非集合映射为@OneToMany,@ ManyToMany或@CollectionOfElements

时间:2016-11-26 20:01:01

标签: java mysql hibernate hibernate-mapping jpa-2.1

我有一个律师表,其中id(int)作为主键,Country表以country_code(String)作为主键。我想在hibernate中使用@JoinTable注释创建第三个表,其中包含两个外键。但是当我运行它时,错误即将来临。不确定如何在第三个表中将一个字符串和一个int映射为外键。

Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: com.test.common.entities.Country.lawyer

这是我的代码

@Entity
@Table(name = "lawyer")
public class Lawyer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "lawyer_batch_no")
    private int lawyerbatchNo;

@ManyToOne(targetEntity = Country.class, cascade = { CascadeType.ALL })
    @JoinTable(name = "lawyer_cscd", joinColumns = {
            @JoinColumn(name = "lawyer_batch_no", referencedColumnName = "lawyer_batch_no") }, inverseJoinColumns = {
                    @JoinColumn(name = "country_code", referencedColumnName = "country_code") })
    private Country country;

getter setter...
}

@Entity
@Table(name = "country")
public class Country {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "country_code")
    protected String country_code;

    @Column(name = "abbreviation")
    protected String abbreviation;

    @Column(name = "name", nullable = false)
    protected String name;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    protected Set<State> state = new HashSet<State>();

    @OneToMany(targetEntity = Lawyer.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
    @JoinTable(name = "lawyer_cscd", joinColumns = {
            @JoinColumn(name = "country_code", referencedColumnName = "country_code") }, inverseJoinColumns = {
                    @JoinColumn(name = "lawyer_batch_no", referencedColumnName = "lawyer_batch_no") })
    private Lawyer lawyer;

getter setter....
}

1 个答案:

答案 0 :(得分:2)

该错误表明private Lawyer lawyer需要是一个集合,因为它是@OneToMany关系。在Country类中,最后一个关系应该是

@OneToMany(targetEntity = Lawyer.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinTable(name = "lawyer_cscd", joinColumns = {
    @JoinColumn(name = "country_code", referencedColumnName = "country_code") }, inverseJoinColumns = {
    @JoinColumn(name = "lawyer_batch_no", referencedColumnName = "lawyer_batch_no") })
private Set<Lawyer> lawyer;
// or a Collection/List/etc.