小编典典

Spring MVC-默认情况下在Controller中设置值

spring-mvc

基于以下映射(位于问题底部),我需要知道如何在Employee类的 “ department_id” 中设置特定值。

Employee             
--------------------------------------------
id  | firstname  | lastname | department_id
--------------------------------------------
1   | David      | Smith    |     1


Department              
-----------
id  | name
-----------
1   | Dep A
2   | Dep B
3   | Dep C

saveEmployee方法(EmployeeController类):

@RequestMapping(value = "/saveEmployee", method = RequestMethod.POST)
public String saveEmployee(@ModelAttribute("employee") Employee employee){
    /*  I need to set the department "id" (foreign key) into the Employee
table directly in this method. */
    int id = 1; // 2 or 3...
    /* The "department_id" in the Employee class should 
       to receive the "id" value. */
    employee.setDepartment(id); // It does not work.
    employeeService.saveEmployee(employee);
    return "redirect:/employees";
}

员工类别:

@Entity
public class Employee{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String firstname;
    private String lastname;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    // Getters and Setters
}

部门课:

@Entity
public class Department{
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    // Getters and Setters
}

阅读 457

收藏
2020-06-01

共1个答案

小编典典

仔细查看您的Employee课程:

@Entity
public class Employee{
    ...

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
    /* THIS IS NOT AN INTEGER DATA TYPE, IT'S A DEPARTMENT DATA TYPE. 
    SO THE SETTER FOR THIS WILL LOOK SOMEWHAT LIKE THIS:*/

    //Setter
    public void setDepartment(Department department) {
        this.department = department
    }

    ...
    // Getters and Setters
}

为了设置一个department创建实例Department,然后通过setter发送它:

@RequestMapping(value = "/saveEmployee", method = RequestMethod.POST)
public String saveEmployee(@ModelAttribute("employee") Employee employee){
    int id = 1; // 2 or 3...

    Department temporaryDepartment = new Department();
    temporaryDepartment.setId(id);

    employee.setDepartment(temporaryDepartment); 
    employeeService.saveEmployee(employee);
    return "redirect:/employees";
}
2020-06-01