mybatis 虽然xml文件有强大的模板标签的处理能力,但实际开发中有时比较复杂的sql还有一部分得在java中预先拼装好,然后放到xml文件中直接使用。但是mybatis是先进行预处理的,所以你传入的片段也好其他也好,都会当做一个值来看待,因此在mybatis中不能使用#{xx}来解析,而是得用${xx}来解析才行。因为#{xx}字符串处理,加单引号,可一定程度的防注入。${xx}直接引用不做处理,比如数字。
代码如下:
StringBuilder dynamicRegionSql = new StringBuilder(); for (int i = 0; i < ipLocation2DTOs.size(); i++) { dynamicRegionSql.append("(region_id=\""); dynamicRegionSql.append(ipLocation2DTOs.get(i).getRegionId()); dynamicRegionSql.append("\""); if (ipLocation2DTOs.get(i).getCityId() != null && ipLocation2DTOs.get(i).getCityId().size() != 0) { dynamicRegionSql.append(" and city in ("); List<String> cityIds = ipLocation2DTOs.get(i).getCityId(); for (int j = 0; j < cityIds.size(); j++) { dynamicRegionSql.append("\""); dynamicRegionSql.append(cityIds.get(j)); dynamicRegionSql.append("\""); if (j != (cityIds.size() -1) ) { dynamicRegionSql.append(","); } } dynamicRegionSql.append(")"); } dynamicRegionSql.append(")"); if (i != (ipLocation2DTOs.size() -1) ) { dynamicRegionSql.append(" or "); } } // System.out.println(dynamicRegionSql); int affectNum = deviceLocationMapper.queryCountByRegion(productModel, dynamicRegionSql.toString());
xml文件中:
<select id="queryCountByRegion" resultType="java.lang.Integer"> SELECT count(*) as num FROM device_location WHERE product_model = #{productModel} and ${dynamicRegionSql} </select>
原文地址:https://www.cnblogs.com/kangjianrong/p/9755605.html
时间: 2024-11-03 21:28:10