Reputation: 1041
I have one lawyer table which is having id(int) as a primary key and Country table having country_code(String ) as a primary key. I want to create third table using @JoinTable annotation in hibernate with two foreign key in it. But when I run it following error is coming. Not sure how to map one string and one int as foreign keys in third table.
Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements: com.test.common.entities.Country.lawyer
This is my code
@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....
}
Upvotes: 2
Views: 14997
Reputation: 73281
The error indicates that private Lawyer lawyer
needs to be a collection as it's a @OneToMany
relationship. In the Country
class, the last relationship should be
@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.
Upvotes: 3