0

I have got two entity classes.

@Entity

public class Employee {

@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "employee_skill", joinColumns = @JoinColumn(referencedColumnName = "employee_id"), inverseJoinColumns = @JoinColumn(referencedColumnName = "skill_id"))
private Collection<Skill> listSkill;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Collection<Skill> getListSkill() {
    return listSkill;
}

public void setListSkill(Skill skill) {
    if (listSkill == null) {
        listSkill = new ArrayList<Skill>();
    }
    listSkill.add(skill);
}

}

@Entity

public class Skill {

@Id
@Column(name = "skill_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;

@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(name = "employee_skill", joinColumns = @JoinColumn(referencedColumnName = "skill_id", insertable = false, updatable = false), inverseJoinColumns = @JoinColumn(referencedColumnName = "employee_id", insertable = false, updatable = false))
private Employee employee;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}   


public Employee getEmployee() {
    return employee;
}

public void setEmployee(Employee employee) {
    this.employee = employee;
}

}

When both of them was UNI-Directional, I can save employee object associate with skill.

NOW when I tried to make it BI-Directional, I am getting sql error saying that Field 'skill_id' doesn't have a default value

I have no idea where did I make it wrong. Could you please point out.

yas
  • 486
  • 1
  • 8
  • 23

1 Answers1

1

You don't have a bidirectional OneToMany association here. You have two independant associations mapped to the same join table. A bidirectional association MUST have a side (the one side, in this case) which is the inverse side of the association, thanks to the mappedBy attribute:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "employee")
private Collection<Skill> listSkill;
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    Shouldn't the annotation be @ManyToMany? – Sõber Aug 30 '15 at 11:42
  • 1
    @Sõber It depends if a skil can be shared by several employees or not. The OP defined it as OneToMany, so I guess that's what he/she wants. – JB Nizet Aug 30 '15 at 11:48
  • @Sõber Thank you for your input. yes, in my requirements, it has to be able to search Employee by skill. So, I think your idea make more sense than mine. +1 – yas Aug 30 '15 at 12:54