反射生成 MyBatisPlus中QueryWrapper动态条件
梁云亮 人气:01.问题
在MyBatisPlus中经常会用到如下所示的代码来构造查询条件:
QueryWrapper<User> queryWrapper = new QueryWrapper<>(); if (userQuery.getId() != null) { queryWrapper.eq("id", userQuery.getId()); } if (userQuery.getName() != null) { queryWrapper.like("name", userQuery.getName()); } if (userQuery.getNickname() != null) { queryWrapper.like("nickname", userQuery.getNickname()); } if (userQuery.getAccount() != null) { queryWrapper.eq("account", userQuery.getAccount()); } if (userQuery.getGender() != null) { queryWrapper.eq("gender", userQuery.getGender()); } if (userQuery.getBirth1() != null) { queryWrapper.ge("birth", userQuery.getBirth1()); } if (userQuery.getBirth2() != null) { queryWrapper.le("birth", userQuery.getBirth2()); } if (userQuery.getTel() != null) { queryWrapper.eq("tel", userQuery.getTel()); } if (userQuery.getEmail() != null) { queryWrapper.eq("email", userQuery.getEmail()); } if (userQuery.getQq() != null) { queryWrapper.eq("qq", userQuery.getQq()); } if (userQuery.getWechat() != null) { queryWrapper.eq("wechat", userQuery.getWechat()); } if (userQuery.getHomePage() != null) { queryWrapper.eq("home_page", userQuery.getHomePage()); } //......... baseMapper.selectPage(page, queryWrapper);
大量这样的代码,可以通过如下所示的反射技术生成,从而一劳永安逸,
2.优化方案
public class APP{ public static void main(String[] args) throws Exception { QueryWrapper<Dept> queryWrapper = new QueryWrapper<>(); Dept dept = Dept.builder() .deptno(1234) // .dname("sales") .loc("NEWYORK") .build(); Method[] methods = Dept.class.getDeclaredMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.contains("get")) { Object res = method.invoke(dept, null); if(res != null){ String columnName = getColumnName(methodName); queryWrapper.eq(columnName,res); } } } System.out.println(queryWrapper);//在此处设置断点,可以查看保存到QueryWrapper中的值 } // 根据getter方法名得到对应表的字段名 public static String getColumnName(String name) { StringBuffer sb = new StringBuffer(); name = name.substring(3, name.length()); //去掉get前缀 char[] chars = name.toCharArray(); for (int i = 0; i < chars.length; i++) { char item = chars[i]; if (item > 65 && item < 90) {//大写字母 sb.append("_"); sb.append((char)(item+32)); }else { sb.append(item); } } return sb.deleteCharAt(0).toString(); } }
加载全部内容