一、xml配置文件【select_in_foreach.xml】
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.test.in"> <select id="SELECT_IN" resultType="map"> select * from JOBS <where> <if test="other != null"> JOB_TITLE = #{other,jdbcType=VARCHAR} </if> <if test="ids != null"> and JOB_ID in <foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> #{item} </foreach> </if> </where> </select> </mapper>
package com.test.dao.impl; import java.util.List; import java.util.Map; import com.test.dao.IDataQuery; import org.apache.ibatis.session.SqlSession; public class BaseDataQueryDAO implements IDataQuery { private SqlSession session; public SqlSession getSession() { return session; } public void setSession(SqlSession session) { this.session = session; } @SuppressWarnings("unchecked") @Override public List<Map> queryData(String str, Map map) { List<Map> list = this.session.selectList(str, map); return list; } @Override public Map queryDataByID(String str, Map pid) { Map map = (Map)this.session.selectOne(str, pid); return map; } }
package com.test.services.impl; import com.test.utils.ConstantEnum; import com.test.utils.MyBatisUtil; import com.test.dao.impl.BaseDataQueryDAO; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; import org.apache.ibatis.session.SqlSession; public class SelectIN extends BaseDataQueryDAO { //查询数据 public String queryJobsList(){ SqlSession session = null; //获取数据库连接 session = MyBatisUtil.createSession(); this.setSession(session); try { <strong><span style="color:#ff6666;">Map<String, Object> params = new HashMap<String, Object>(); //方法一,使用数组 //String[] ids = {"AD_PRES","AD_VP"}; //方法二,使用List List<String> ids = new ArrayList<String>(); ids.add("AD_PRES"); ids.add("AD_VP"); params.put("ids", ids); params.put("other", "President"); //参数map List<Map> map = this.queryData("com.test.in.SELECT_IN", params);</span></strong> if(map.isEmpty()){ return ConstantEnum.FAILURE_SEARCHDATA; } JSONObject result = new JSONObject(); JSONObject table = new JSONObject(); table.put("row", map); result.put("datas", table); result.put("result", "1"); result.put("info", "查询成功!"); System.out.println(result); return result.toString(); } catch (Exception e) { e.printStackTrace(); return ConstantEnum.ERROR_SEARCHDATA; }finally{ MyBatisUtil.closeSession(session); } } //测试 public static void main(String[] args) { SelectIN selectIN = new SelectIN(); selectIN.queryJobsList(); } }
参考
http://www.suyunyou.com/aid5.html
http://www.2cto.com/database/201301/185980.html
http://fireinjava.iteye.com/blog/1779420