Java代码里如何拼接SQL语句到mybatis的xml
关键语句:
StringBuilder whereSql = new StringBuilder(); whereSql.append("SQL");
实现类:
public List getList(Map<String, Object> map) { List<Map<String, Object>> rs = new ArrayList<Map<String, Object>>(); try { StringBuilder whereSql = new StringBuilder(); if (map.get("userName").toString().length()>0) { whereSql.append(" AND a.userName in ('" + map.get("userName").toString().replaceAll(",", "\',\'") + "')");//不为空时加入查询条件 } if (map.get("CURRENTPAGE").toString().length()>0 && map.get("PAGESIZE").toString().length()>0) {//前端有传分页参数时就添加分页查询条件 int currenpage = Integer.parseInt(map.get("CURRENTPAGE").toString()); int pagesize = Integer.parseInt(map.get("PAGESIZE").toString()); currenpage = ((currenpage - 1) * pagesize); whereSql.append(" limit " + currenpage + "," + pagesize); } rs = wmTblWorkorderMapper.getList(whereSql.toString()); return rs; } catch (Exception e) { e.printStackTrace(); } return null; }
mapper:
List<Map<String,Object>> getList(@Param("whereSql") String whereSql);
mapper对应的xml:
<select id="getList" resultType="HashMap"> SELECT * FROM user a WHERE 1=1 ${whereSql} </select>
mybatis中拼接sql语句的特殊符号表示
需要在mybatis中,使用到大于号,小于号等等拼接sql语句,一般有以下XML转义字符 :
XML转义字符
< < 小于号
> > 大于号
& & 和
' ' 单引号
" " 双引号
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)