天天看点

使用反射完成mybatis-plus自动装配查询条件

先上DO代码:

@Data
@TableName("dict")
public class DictDo {
    @TableId(type=IdType.AUTO)
    private String id;
    @TableField("`key`")
    private String key;
    private String value;
    private String memo;
}      

此处使用了lombok,自动生成对象方法(此处是否与我们的思想有异曲同工之妙呢)!

使用原生的查询条件拼装:

public List<DictDo> selectListEq(DictDo one) {
        QueryWrapper<DictDo> wrapper = new QueryWrapper<>();
        if (null != one.getId()) {
            wrapper.eq("id", one.getId());
        }
        if (null != one.getKey() && !"".equals(one.getKey())) {
            wrapper.eq("`key`", one.getKey());
        }
        if (null != one.getValue() && !"".equals(one.getValue())) {
            wrapper.eq("value", one.getValue());
        }
        if (null != one.getMemo() && !"".equals(one.getMemo())) {
            wrapper.eq("memo", one.getMemo());
        }
        return dictDao.selectList(wrapper);
    }

      

如上所示,每个对象如果只有几条属性还好说,但是如果有几十条属性呢?

我们应该想到所有重复的劳动都是低价值的、可以被替代的!

工具代码:

public static QueryWrapper parseQuery(Object service) throws Exception {
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        Class<? extends Object> doClass = service.getClass();
        Method[] methods = doClass.getDeclaredMethods();
        Field[] fields = doClass.getDeclaredFields();
        for (Field field : fields) {
            for (Method method : methods) {
                if (method.getName().equalsIgnoreCase("get" + field.getName())) {
                    String value = doClass.getDeclaredMethod(method.getName()).invoke(service) == null ? ""
                            : (String) doClass.getDeclaredMethod(method.getName()).invoke(service);
                    if (null != value && !"".equals(value)) {
                        wrapper.eq("`"+field.getName()+"`", doClass.getDeclaredMethod(method.getName()).invoke(service));
                        break;
                    }
                }
            }
        }
        return wrapper;
    }

      

Service进行调用:

/**
  * 按对象属性匹配
  * @throws Exception 
  */
    public List<DictDo> selectListEq(DictDo one) throws Exception {
  QueryWrapper<DictDo> wrapper = ParamSettingUtil.parseQuery(one);
  return dictDao.selectList(wrapper);
    }      

进行测试:

@SuppressWarnings("unchecked")
    @Test
    public void testSelect() {
  System.out.println("## testSelect");
  DictDo dictDo=new DictDo();
  dictDo.setKey("233");
  QueryWrapper<DictDo> wrapper;
    try {
    wrapper = ParamSettingUtil.parseQuery(dictDo);
    List<DictDo> dictDos= dictDao.selectList(wrapper);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    
    }      

测试结果:

使用反射完成mybatis-plus自动装配查询条件

如上图看到,我们新加进去的条件已经生效了!

继续阅读