Reputation: 553
forum member I am having one problem with the insertion of data using Hibernate JPA framework.
I am having one-to-many relationship between task and resources.
my task model is like below shown code.
@Entity
@Table(name = "task")
public class Task {
private Integer id;
private Set<Employee> employee = new HashSet<Employee>(0);
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToMany(cascade = CascadeType.ALL, fetch =FetchType.EAGER)
@JoinTable(name = "task_employee", joinColumns = { @JoinColumn(name = "taskid") }, inverseJoinColumns = { @JoinColumn(name = "employeeid") })
public Set<Employee> getEmployee() {
return employee;
}
public void setEmployee(Set<Employee> employee) {
this.employee = employee;
}
}
and my Employee model is
@Entity
@Table(name = "employee")
public class Employee {
private Integer id;
private String firstname;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "firstname")
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
}
I am able to insert the record successfully when the
1. Task id is 1 and employeeid is 1,
2. Task id is 1 and employeeid is 2,
3. Task id is 2 and employeeid is 3,
but the error occurs when the employee id is duplicated like below insertion.
4. Task id is 1 and employeeid is 1
it gives me error
79512 [http-8080-4] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
79517 [http-8080-4] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '2' for key 'employeeid'
79517 [http-8080-4] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
What's wrong with my code? Please, help me!!!
Upvotes: 2
Views: 755
Reputation: 120851
You have a OneToMany relation ship. This mean a task can have many employee, but a single employee can have only on task!
error occurs when the employee id is duplicated
But you violated (or tryed to violate) the second part of that constraint
So you should use a ManyToMany relation ship.
Upvotes: 1