Create an entity class and encapsulate the Employee class
@Data Role: get getter() and setter() method
@AllArgsConstructor role: construct full parameter method
@NoArgsConstructor role: construct empty parameter method
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private String name;
private String department;
private String number;
private Integer salary;
}
Create the EmployeeController class
import com.example.helloworld.pojo.Employee;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class EmployeeController {
//获取单个对象信息
@GetMapping("/findOneEmployee")
public Employee getEmployee(){
return new Employee("张三","销售部","A3333",9000);
}
//获取多个对象信息
@GetMapping("/findMultiEmployee")
public List<Employee> getEmployees(){
return Arrays.asList(
new Employee("张三","销售部","A3333",9000),
new Employee("黄三","技术部","B3333",19000),
new Employee("李三","财务部","C3333",10000),
new Employee("王三","销售部","A2222",9000)
);
}
//新增一个对象
@PostMapping("/addOneEmployee")
public String addEmployee(@RequestBody Employee employee){
System.out.println("添加:"+ employee); //后台返回添加员工信息
return "成功添加一个对象!";//前端返回添加成功信息
}
//新增多个对象
@PostMapping("/addMultiEmployee")
public String addEmployees(@RequestBody List<Employee> employees){
employees.forEach(employee -> {System.out.println("添加:"+employee);});
return "成功添加多个对象!";
}
}