Home > Back-end >  Springboot date entity problem "Failed to convert value of type 'java.lang.String' to
Springboot date entity problem "Failed to convert value of type 'java.lang.String' to

Time:06-23

When I tried to get with these url : http://www.localhost:8080/api/employee/search?startDate=2000-10-22&salary=10000

This error message shows up : "Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date] for value '2000-10-22'; nested exception is java.lang.IllegalArgumentException"

Params : startDate = 2000-10-22 salary = 10000

What is the problem here ?

Employee Class :

@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 in my repository :

  @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);

ServiceImpl:

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

Controller :

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

CodePudding user response:

This is because by default, Spring cannot convert String parameters to any date or time object.

Use this instead.

@RequestParam @DateTimeFormat(pattern= "yyyy-MM-dd") Date startDate

CodePudding user response:

problem is java convert string to date you can try this

@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));
}
  • Related