我想这样发布:
[{
"employeeid": "1111",
"employeename": "YOA"
},
{
"employeeid": "2222",
"employeename": "OYA"
}]
我的控制器是这样的:
@PostMapping("/api/employee/save")
public Employee createEmployee(@Valid @RequestBody List<Employee> employee) {
return employeeService.save(employee);
}
型号:
@Entity
@Table(name="EMPLOYEE")
public class Employee implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
int id;
@Column(name = "EMP_ID")
int employeeid;
@Column(name = "EMPLOYEE_NAME")
String employeename;
//GETTER AND SETTER
}
当我发布数据时,出现的错误如下:
{
"timestamp": "2018-07-13T03:36:25.898+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Invalid property 'id' of bean class [java.util.ArrayList]: Could not find field for property during fallback access!",
"path": "/api/employee/save"
}
服务内容:
public interface employeeService{
Employee save(List<Employee> employee);
}
服务展示次数:
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
@Override
public Employee save(List<Employee> employee) {
return employeeRepository.save(employee);
}
}
仓库:
public interface EmployeeRepository extends Repository <Employee, Long>
Employee save(List<Employee> employee);
}
错误描述是这样的:
Bean类[java.util.ArrayList]的无效属性'id':在后备访问期间找不到属性的字段!
当使用saveAll()时,我得到错误消息:找不到类型为Employee的属性saveAll
有谁可以帮助我吗?
我已经修改了我的问题。
问候,
我
最佳答案
问题在这条线
public Employee createEmployee(@Valid @RequestBody List<Employee> employee) {
return employeeService.save(employee); // Problem
}
employeeService.save
在您的情况下只能采用一个实体对象Employee
有2种方法
1。
public Boolean createEmployee(@Valid @RequestBody List<Employee> lstEmployee) {
try{
for(Employee emp : lstEmployee){
employeeService.save(employee);
}
return true;
}catch(Exception e){}
return false;
}
2。
使用saveAll代替
public Employee createEmployee(@Valid @RequestBody List<Employee> employee) {
return employeeService.saveAll(employee);
}
编辑1:
添加服务类后,您似乎正在手动实现,因此
选项1:
我建议您直接在控制器类中使用
EmployeeRepository
。就像通过手动覆盖那里的方法,您实际上并没有
享受使用存储库的好处
@Autowired
EmployeeRepository employeeRepository;
@PostMapping("/api/employee/save")
public Employee createEmployee(@Valid @RequestBody List<Employee> lstEmployee) {
return employeeRepository.saveAll(lstEmployee);
}
选项2:
从长远来看,像这样更改您的实现。对象可能有一些错误,但应该可以给您一个提示
public interface employeeService{
Employee save(Employee employee);
public <S extends User> List<S> saveAll(Iterable<S> entites);
}
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository employeeRepository;
@Override
public Employee save(Employee employee) {
return employeeRepository.save(employee);
}
@Override
public List<Employee> saveAll(List<Employee> employee) {
return employeeRepository.saveAll(employee);
}
}