众所周知,jdbcTemplate 的查询可以通过 ? 方法,带查询参数方式实现,一来语句更加简洁,不用拼凑字符串方式,而来还可以防止SQL注入,但是碰到in查询 采用 多个参数
select * from a where in (?)
方式的就存在问题了,经过反复试验,网上解决方法用的是另外一个namejdbcTemplate来解决,但是本人还是喜欢jdbcTemplate,经过反复摸索,其实in(?)方式还是可以实现,只是要固定?查询参数
比如
#对于两个参数写法
pSelectSql =select * from a where in (?,?)
jdbcTemplate.query(pSelectSql, 类 , 参数1,参数2)
#3个参数
pSelectSql =select * from a where in (?,?,?)
以此类推
但是这样写法十分麻烦,就写了一个工具实现类,具体解决方案如下
工具类
/**
* in 查询 SQL组合类
* 使用用法
* SqlConditionIn in = new SqlConditionIn();
* in.addValue(xxxx);
*
* if (in.isIn()) {
* strCondition += " and b_unit_id in (" + in.getConditions() + ")";
* args.addAll(in.getObjs());
* }
*/
public class SqlConditionIn {
private String conditions="";
private List<Object> objs = new ArrayList<>();
/**
* 是否组成in条件
* @return
*/
public boolean isIn()
{
if (objs.size()>0)
return true;
else
return false;
}
public void addValue(Object ob)
{
objs.add(ob);
if (!conditions.equals(""))
conditions+=",?";
else
conditions="?";
}
public String getConditions() {
return conditions;
}
public List<Object> getObjs() {
return objs;
}
}
具体使用方式
List<Object> args = new ArrayList<>();
//写入in c查询参数
for (BUnitUserinfoEO bUnitUserinfoEO : list) {
//ids+=",'"+bUnitUserinfoEO.getB_unit_id()+"'";
in.addValue(bUnitUserinfoEO.getB_unit_id());
}
//组合sql
String sql=“select * from a where 1=1
if (in.isIn()) {
strCondition += "and b_unit_id in (" + in.getConditions() + ")";
args.addAll(in.getObjs());
sql+=strCondition;
}
//查询
jdbcTemplate.query(sql, 类 , args.toArray());