java - Spring MVC - Setting values by default in Controllers -


based on following mapping (at bottom of question) need know how set specific value in "department_id" in employee class.

employee              -------------------------------------------- id  | firstname  | lastname | department_id -------------------------------------------- 1   | david      | smith    |     1    department               ----------- id  | name ----------- 1   | dep 2   | dep b 3   | dep c 

saveemployee method (employeecontroller class):

@requestmapping(value = "/saveemployee", method = requestmethod.post) public string saveemployee(@modelattribute("employee") employee employee){     /*  need set department "id" (foreign key) employee table directly in method. */     int id = 1; // 2 or 3...     /* "department_id" in employee class should         receive "id" value. */     employee.setdepartment(id); // not work.     employeeservice.saveemployee(employee);     return "redirect:/employees"; } 

employee class:

@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 , setters } 

department class:

@entity public class department{     @id     @generatedvalue(strategy=generationtype.auto)     private int id;     private string name;     // getters , setters } 

look @ employee class:

@entity public class employee{     ...      @manytoone     @joincolumn(name = "department_id")     private department department;     /* not integer data type, it's department data type.      setter this:*/      //setter     public void setdepartment(department department) {         this.department = department     }      ...     // getters , setters } 

in order set department create instance department , send through 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"; } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -