问题
当在写查询语句的时候需要传入多个参数的时候该怎么办呢?
方法一:不需要写parameterType参数
//传参
public List<XXXBean> getXXXBeanList(String xxId, String xxCode);
// sql语句
<select id="getXXXBeanList" resultType="XXBean">
select t.* from tableName where id = #{0} and name = #{1}
</select>
就不使用parameterType, 直接用索引,从0开始
方法二:基于注解(最简单)
//加注解传参
public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code);
//sql语句
<select id="getXXXBeanList" resultType="XXBean">
select t.* from tableName where id = #{id} and name = #{code}
</select>
@Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中(一般通过#{}的方式,${}会有sql注入的问题)
方法三:Map封装
//传参
HashMap <String,Object> map=new HashMap<String,Object>();
map.put("userName","zhangsan");
map.put("password","123456");
public List<XXXBean> getXXXBeanList(HashMap map);
//sql语句
<select id="getXXXBeanList" parameterType="map" resultType="XXBean">
select 字段... from XXX where id=#{userName} code = #{passWord}
</select>
方法四:List封装
//传入参数
public List<XXXBean> getXXXBeanList(List<String> list);
//sql语句
<select id="getXXXBeanList" resultType="XXBean">
select 字段... from XXX where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
最后
传递list和map在资源消耗上肯定远大于方法一和方法二,但是有一些特殊的情形需要传递list,比如你需要传递一个id集合并批量对id进行sql操作然后再返回等等。所以都需要了解。