hibernate SpringBoot Date实体问题“无法将‘java.lang.String’类型的值转换为所需的类型‘java.util.Date’

nbnkbykc  于 2022-11-14  发布在  Spring
关注(0)|答案(2)|浏览(166)

当我尝试使用这些url时:http://www.localhost:8080/api/employee/search?startDate=2000-10-22&salary=10000
此错误消息显示:“无法将类型为‘java.lang.String’的值转换为所需的类型‘java.util.Date’;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法将值‘2000-10-22’的类型[java.lang.String]转换为类型[@org.springframework.web.bind.annotation.RequestParam java.util.Date;嵌套异常为java.lang.IlLegalArgumentException”“
参数:开始日期=2000-10-22工资=10000
这里出了什么问题?
员工类别:

@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @NotBlank
    private String nationalId;

    @NotBlank
    private String name;

    @NotBlank
    private String surname;

    private Integer salary;

    @JoinColumn(name="start_date")
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date startDate;

    private String office;

    private String department;

在我的存储库中查询:

@Query("Select e FROM Employee e  " +
            "where " +
            " (:startDate is NULL or e.startDate > :startDate) " +
            " AND " +
            " (:salary is NULL or e.salary > :salary) ")
    List<Employee> searchEmployees(Date startDate,Integer salary);

服务导入:

@Override
    public List<Employee> searchEmployees(Date startDate,Integer salary){
        List <Employee> employees = employeeRepository.searchEmployees(startDate,salary);
        return employees;
    }

控制器:

@GetMapping(path="/search")
    public ResponseEntity<List<Employee>> searchEmployees(@RequestParam("startDate") Date startDate,
                                                          @RequestParam("salary") Integer salary){
        return ResponseEntity.ok(employeeService.searchEmployees(startDate,salary));
    }
tkqqtvp1

tkqqtvp11#

这是因为默认情况下,Spring不能将字符串参数转换为任何日期或时间对象。
改用这个吧。
@RequestParam @DateTimeFormat(pattern= "yyyy-MM-dd") Date startDate

soat7uwm

soat7uwm2#

问题是Java将字符串转换为日期,您可以尝试这样做

@GetMapping(path="/search")
public ResponseEntity<List<Employee>> searchEmployees(@RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date startDate,
                                                      @RequestParam("salary") Integer salary){
    return ResponseEntity.ok(employeeService.searchEmployees(startDate,salary));
}

相关问题