网上很多例子都是mybatis批量查询的时候都是用in子句,但是,如果一个查询的参数封装成一个对象,并且查询参数又是一个集合的时候,该如何写呢
下面是一个例子:
想使用:
List<CDMAView> list = dao.selectByList(listP);
接口这样写:
public interface CDMADao {
public List<CDMAView> selectByList(List<CDMASearchParameter> list);
//CDMASearchParameter是一个实体对象,专门用来封装查询参数,返回一个封装了vo的集合对象
}
xml文件这样写:
<select id="selectByList" parameterType="java.util.List" resultMap="cdmaResult">//这里返回的结果自然也是一个集合
select * from cdma where
<foreach collection="list" separator="or" open="(" close=")" index="index" item="item">
mnc=#{item.sid} and lac=#{item.nid} and cell=#{item.bid}
</foreach>
</select>
<resultMap type="cn.juhe.vo.CDMAView" id="cdmaResult">
<result property="sid" column="mnc"/>
<result property="nid" column="lac"/>
<result property="bid" column="cell"/>
<result property="lon" column="lng"/>
<result property="lat" column="lat"/>
<result property="o_lon" column="o_lng"/>
<result property="o_lat" column="o_lat"/>
<result property="raggio" column="precision"/>
<result property="address" column="address"/>
</resultMap>
为什么要突出or呢,可以看控制台打印的失去了语句:
DEBUG cn.juhe.dao.CDMADao.selectByList - ==> Preparing: select * from cdma where ( mnc=? and lac=? and cell=? or mnc=? and lac=? and cell=? )
可以先把这sql语句在数据库中测试一下,看看能不能直接查询出结果,如果可以,那肯定就没有问题了
重点是,在使用foreach的时候要拼接到sql语句