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

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

Employee             

--------------------------------------------

id | firstname | lastname | department_id

--------------------------------------------

1 | David | Smith | 1

Department

-----------

id | name

-----------

1 | Dep A

2 | Dep B

3 | Dep C

@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

}

回答:

仔细查看您的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";

}

以上是 Spring MVC-默认情况下在Controller中设置值 的全部内容, 来源链接: utcz.com/qa/406874.html

回到顶部