使用反射完成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();
			}
			
	}

測試結果:
在這裏插入圖片描述
如上圖看到,我們新加進去的條件已經生效了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章