Mybatis按顺序获取数据

sql语句select * from producttg where hospitalcode in (1,2,3)  获取到的数据并不是按照条件1,2,3的顺序排列,如果要成下面形式(mybatis语句)

select * 
from producttg 
where productno in ${productnolist}
order by CHARINDEX(','+ltrim(productno)+',',',${productnostr}')

  其中输入为productnolist(String类型),productnostr(String类型)

productnolist的格式为:(1,2,3)
productnostr的格式为:1,2,3,

  java中将List转成上述两种字符串格式的代码为:

        //拼接成:('00401','01001','00301','02001') 
	public static String ListToString1(List<String> inputlist){
		String result="('";
		for (int i= 0; i<inputlist.size();i++) {
			if(i==inputlist.size()-1){
				result=result+inputlist.get(i)+"')";
			}else{
				result=result+inputlist.get(i)+"','";
			}
		}
		return result;
	}     

  

        //拼接成:00401,01001,00301,02001,
	public static String ListToString2(List<String> inputlist){
		String result ="";
		for (String item : inputlist) {
			result =result+item+",";
		}
		return result;
	}    

  这样就完成了,按照productno in 多个条件的顺序依次查出的需求,注意:mybatis语句中取输入数据用的是${ },而不是#{ }

  1.#{ }可以防止注入,${ }不能防止注入

       2.#{ }传入占位符,${ }传入字符串

  3.order by需要使用${ }

posted @ 2017-11-15 09:36  nothing_fish  阅读(1882)  评论(0编辑  收藏  举报