无法在hibernate中将数据插入链接表中的多对多

时间:2017-07-12 06:15:45

标签: mysql hibernate spring-mvc

关系就像

  • 一个项目可以有很多员工。

在JSP上,在选择项目时,将填充所有员工。 任务的文本框。

为所选项目提供任务名称,为该任务选择员工并保存。

我可以保存任务但不能保存在链接表中。

实体类是,

员工,任务,项目

员工

@Entity
@Table(name="Employee")
public class Employee implements Serializable{

    @Id
    @Column(name="employee_id")
    private String employeeId;

    @Column(name="employee_name")
    private String employeeName;

    @ManyToMany(mappedBy="employees")
    private Set<Task> tasks;
}

项目

@Entity
@Table(name = "Project")
public class Project implements Serializable {

    @Id
    @Column(name = "project_id")
    private int projectId;

    @Column(name = "project_name")
    private String projectName;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "PROJECT_EMPLOYEE", 
    joinColumns = { @JoinColumn(name = "project_id") }, 
    inverseJoinColumns = { @JoinColumn(name = "employee_id") })
    private Set<Employee> employees;

}

任务

@Entity
@Table(name = "Task")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "task_id")
    private int taskId;

    @Column(name = "task_details")
    private String taskDetails;

    @Temporal(TemporalType.DATE)
    @Column(name = "start_date")
    private Date startDate;

    @Temporal(TemporalType.DATE)
    @Column(name = "end_date")
    private Date endDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "project_id", nullable = false)
    private Project project;

    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name = "Task_Employee", joinColumns = { @JoinColumn(name = "task_id") }, inverseJoinColumns = {
            @JoinColumn(name = "employee_id") })
    @Embedded
    private Set<Employee> employees;
}

无法保存到Task_Employee表中。

Dao代码:

从jsp,我得到所有字符串值并创建这样的任务对象,empView是从JSP页面获取的视图对象,并创建要在dao中保存的Task对象。

Set<Employee> empSet = new HashSet<Employee>();
for(String employeeId : empView.getEmployees()) {
    Employee emp = new Employee();
    emp.setEmployeeId(employeeId);
    //emp.setEmployeeName("aaa");
    //emp.setProject(new Project(empView.getProjectId()));
    empSet.add(emp);
}

return new Task(0, empView.getTaskDesc(), new Project(empView.getProjectId()), toDate(empView.getStartDate()),
                toDate(empView.getEndDate()), empSet);

保存上面返回的任务对象。

sessionFactory.openSession().save(task);

由于

0 个答案:

没有答案