1 2 | StringBuilder whereSql = new StringBuilder(); whereSql.append( "SQL" ); |
实现类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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:
1 | List<Map<String,Object>> getList( @Param ( "whereSql" ) String whereSql); |
mapper对应的xml:
1 2 3 | < select id = "getList" resultType = "HashMap" > SELECT * FROM user a WHERE 1=1 ${whereSql} </ select > |
需要在mybatis中,使用到大于号,小于号等等拼接sql语句,一般有以下XML转义字符 :
XML转义字符
< < 小于号
> > 大于号
& & 和
' ' 单引号
" " 双引号
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。