Ullas Sharma
Ullas Sharma

Reputation: 450

Handling Date as Request Params in Spring Boot getting error

I'm working on a requirement where i'm passing key and date as @RequestParam, to fetch the list of records between created_date and modified_date from MSSQL Server db.

here key is mandatory and date is optional.

I've got a GET request that sends key and date as @RequestParam to Spring Controller.

@GetMapping(value = "/getValueFromGC", produces = { MediaType.APPLICATION_JSON_VALUE })
public List<GcAppConfig> getValueFromGC(@RequestParam String key, @RequestParam(required = false)@DateTimeFormat(pattern = "dd-MM-yyyy") Date date) {
   //if date param is not null
    if(date != null) {
        return gcAppConfig.getValueFromGC(key,date);
    }
   //if date param is null fetching the list of all available records
    else {
        return gcAppConfig.getValueFromGC(key);
    }

}

Controller fetches the records if date param is null. i.e

URL: localhost:8082/getValueFromGC?key=TOLERANCE&date=

while passing the date param in below format

Url:getValueFromGC?key=TOLERANCE&date=21-01-2019

Here is my service gcAppConfig which fetches the record between created_date and modified_date bypassing date

Note:created_date and modified_date are in datetime2 format

@Query(" Select g from GcAppConfig g where g.isActive=1 and g.keys= :keys" + 
        "  and  :date >=" + 
        "  CAST(g.createdDate AS DATE) and " + 
        " :date <= " + 
        "  CAST(g.modifiedDate AS DATE) ")
public List<GcAppConfig> getValueFromGC(@Param("keys")String keys, @Param("date")Date date);

Could not resolve requested type fo CAST: DATE

Please correct me in Query also if it is wrong. Any suggestion welcomed. thanks in advance.

Upvotes: 0

Views: 1836

Answers (1)

Pijotrek
Pijotrek

Reputation: 3021

It has nothing to do with your Repository. Error is at the Controller level. Do you really have to use java.sql.Date? If you used java.util.Date it should work fine, especially with @DateTimeFormat("yyyy-MM-dd") annotation for the parameter.

Upvotes: 1

Related Questions