Passing optional parameters to @Query of a Spring Data Repository method

自闭症网瘾萝莉.ら 提交于 2019-12-05 10:58:52

I solved this problem using QueryDSL with Spring Data. There is a good tutorial on baeldung.com. With QueryDSL your spring data query is simply personRepository.findAll(predicate);.

You can use an object to represent the multiple request parameters and declare their type to be Optional<String> name; etc.

Then you can build the predicate (assuming you setup you stuff as in the linked tutorial):

Predicate predicate = new MyPredicateBuilder().with("name", ":", name.orElse(""))
.with("birthDate", ":", birthDate.orElse(""))
.with("town", ":", town.orElse(""))
.build();

I personally modified it so it didn't use the ":" as they are redundant for my usage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!