@service 层
public List<T> getAllObject(int toPage, int pageSize,
String name, String type, int status) {
String sql = "" ;
Object[] params = new Object[3];//最多有几个参数就写多大
int index = 0;
if (null!=name&&!name.equals("")) {
sql += " WHERE name LIKE CONCAT('%',?,'%') ";
params[index] = name;
index++;
}
if (null!=taskType&&!taskType.equals("")) {
if(index==0){
sql += "WHERE type= ? ";
}else{
sql += " AND type= ? ";
}
params[index] = taskType;
index++;
}
if (status== 1 || status== 0) {
if(index==0){
sql += "WHERE status= ? ";
}else{
sql += " AND status= ? ";
}
params[index] = status;
index++;
}
Object[] paramsEnd = new Object[index];
System.arraycopy(params, 0, paramsEnd, 0, index); //把params的内容复制给paramsEnd,这是最终的参数数组
return objectDao.getAllObject(sql,paramsEnd);
@dao层
public List<T> getAllObject(String str, Object[] param)
throws Exception {
String sql = SELECT_OBJECT_ALL+str;
List<T> task = new ArrayList<T>();
task = jdbcTemplate.query(sql,param,
new TaskRowMapper());
return task;
}
使用System.arraycopy()实现数组之间的复制
System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。其函数原型是: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src:源数组; srcPos:源数组要复制的起始位置; dest:目的数组; destPos:目的数组放置的起始位置; length:复制的长度。 注意:src and dest都必须是同类型或者可以进行转换类型的数组. 有趣的是这个函数可以实现自己到自己复制,比如: int[] fun ={0,1,2,3,4,5,6}; System.arraycopy(fun,0,fun,3,3); 则结果为:{0,1,2,0,1,2,6}; 实现过程是这样的,先生成一个长度为length的临时数组,将fun数组中srcPos 到srcPos+length-1之间的数据拷贝到临时数组中,再执行System.arraycopy(临时数组,0,fun,3,3).
此文为根据csdn上文章思路创作的代码片段,本段代码为自己编写,但是思路为spring jdbc多条件查询(参数化传参,防止sql注入风险)
原文为https://blog.csdn.net/fangqun663775/article/details/50581683