论坛成员我在使用Hibernate JPA框架插入数据时遇到了一个问题。
我在任务和资源之间有一对多的关系。
我的任务模型如下图所示。
@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;
}
}
我的员工模型是
@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;
}
}
我能够在
时成功插入记录1。任务ID为1,employeeid为1,
2。任务ID为1,employeeid为2,
第3。任务ID为2,employeeid为3,
但是当员工ID重复时会发生错误,例如下面的插入。
4。任务ID为1,employeeid为1
它给了我错误
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
我的代码出了什么问题?拜托,帮帮我!!!
答案 0 :(得分:1)
您有OneToMany关系。这意味着任务可以拥有许多员工,但是一个员工只能执行任务!
员工ID重复时发生错误
但是你违反了(或试图违反)该约束的第二部分
所以你应该使用ManyToMany关系。