Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data rest, java.util.Date in url param?

Tags:

java

rest

spring

I have a simple POJO named as Check. And I have a simple rest repository:

@RepositoryRestResource(collectionResourceRel = "check",path = "check")
public interface RestCheckRepo
        extends JpaRepository<Check,Integer> {

    public List<Check> findByShopName(@Param("shop") String shop);

    public List<Check> findByDateTime(@Param("dt")Date dt);

    public List<Check> findByShopNameAndDateTime(@Param("shop")String shop, @Param("dt")Date dt);

    public List<Check> findByShopNameAndDateTimeBetween(@Param("shopName") String shop,
                                                        @Param("start")Date t1,
                                                        @Param("end") Date t2);


}

All works fine!! But I don't know how to implement a request handler using java.util.Date as a @RequestParam. Example: http://localhost:8080/check/search/findByDateTime?dt={value}

UPDATE Request http://localhost:8080/check/search/findByDateTime?dt=2015-08-10T13:47:30 ---> Response:

{
    "cause": {
        "cause":null,
        "message":null
    },
    "message":"Failed to convert from type java.lang.String to type @org.springframework.data.repository.query.Param java.util.Date for value '2015-10-07T15:04:46Z'; nested exception is java.lang.IllegalArgumentException"
}
like image 551
Programmer Avatar asked Oct 08 '15 10:10

Programmer


2 Answers

Solution of @kucing_terbang will work, otherwise there is a simpler solution, you need do this:

public List<Check> findByShopNameAndDateTime(
    @Param("shop")String shop, 
    @DateTimeFormat(your-format-comes-here)@Param("dt")Date dt);
like image 187
Jaiwo99 Avatar answered Oct 04 '22 04:10

Jaiwo99


You can register a custom editor so that spring able to pass the parameter to the argument. example

@InitBinder
public void dataBinding(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
} 
like image 28
kucing_terbang Avatar answered Oct 04 '22 03:10

kucing_terbang