最近在学springboot jpa,在按条件查询的时候有很多的方法,一开始写的每个方法都会写一个对应的controller,但是这样的方法太多。
//… where x.firstname = 1?
List<User> findByFirstName(String firstName);
List<User> findByFirstNameIs(String firstName);
List<User> findByFirstNameEquals(String firstName);
//… where x.startDate between 1? and ?2
List<User> findByStartDateBetween(Date beginDate,Date endDate);
//… where x.age < ?1
List<User> findByAgeLessThan(Integer age);
//… where x.age ⇐ ?1
List<User> findByAgeLessThanEqual(Integer age);
//… where x.age > ?1
List<User> findByAgeGreaterThan(Integer age);
//… where x.age >= ?1
List<User> findByAgeGreaterThanEqual(Integer age);
//… where x.startDate > ?1
List<User> findByStartDateAfter(Date startDate);
//… where x.startDate < ?1
List<User> findByStartDateBefore(Date startDate);
//… where x.age is null
List<User> findByAgeIsNull(Integer age);
//… where x.age not null
//findByAge(Is)NotNull 其中is可省略
List<User> findByAgeNotNull(Integer age);
//… where x.firstname like ?1
List<User> findByFirstNameLike(String firstName);
//… where x.firstname not like ?1
List<User> findByFirstNameNotLike(String firstName);
//… where x.firstname like ?1 (parameter bound with appended %)
List<User> findByFirstNameStartingWith(String firstName);
//… where x.firstname like ?1 (parameter bound with prepended %)
List<User> findByFirstNameEndingWith(String firstName);
//… where x.firstname like ?1 (parameter bound wrapped in %)
List<User> findByFirstNameContaining(String firstName);
//… where x.age = ?1 order by x.lastname desc
List<User> findByAgeOrderByLastNameDesc(Integer age,String lastName);
//… where x.lastname <> ?1
List<User> findByLastNameNot(String lastName);
//… where x.age in ?1
List<User> findByAgeIn(Collection<Integer> ages);
//… where x.age not in ?1
List<User> findByAgeNotIn(Collection<Integer> ages);
//… where x.active = true
List<User> findByActiveTrue();
//… where x.active = false
List<User> findByActiveFalse();
//… where UPPER(x.firstame) = UPPER(?1)
List<User> findByFirstNameIgnoreCase(String firstName);
然后我想能否写一些controller,然后把查询条件当成一个参数,再用switch去选择合适的查询方法
@RequestMapping("find")
public List<User> findUser(HttpServletRequest request){
String method = request.getParameter("method")==null?"":request.getParameter("method");
switch(method) {
case "findByAgeLessThan":return jpaUserRepository.findByAgeLessThan(Integer.valueOf(request.getParameter("age")));
case "findByFirstName":return jpaUserRepository.findByFirstName(request.getParameter("firstName"));
//....
default:return null;
}
}
这样写会有什么问题么