最近在学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;
}
}
这样写会有什么问题么
不建议这样使用。可读性太差,效验复杂,代码杂乱,容易出问题。
首先你这个接口得参数可以有无数种变化,假设你想写个接口文档给后面开发的人看,那太比较蛋疼。
其次,你不可能参数一过来就开始查询db,正常业务中,肯定要效验参数,然后有一些其他业务。这样的话你这个controller中的方法
会变的无限复杂,没有可读性。
另外假设你这个controller中有处理异常的地方。可能导致整个controller不可用,如果一个controller的话只会影响一个接口,
而你这相当全部,除非你就当做路由使用,但已经有路由了,又何必多此一举呢!
正常情况下,影响,不大得,因为你这个只是多了一步对比的,不是查询数据库(相对需要很久的时间),或者是走加锁的方法,只要不是这
种,对性能的影响不是很大的。
这样对性能没啥影响,但是从业务来看的话,可读性不高
不建议这样做,你这样相当于这个controller做了系统路由的工作,不符合软件开发单一职责原则。