当传入的参数仅为一个参数的时候,参数的接收只需要写个占位符即可,名称写什么都无所谓。
<select id="getById" parameterType="java.lang.Integer" resultMap="userMap">
select * from user where id=#{xxx}
</select>
当传入的参数为多个的时候,参数的接收为为参数的索引,如果参数类型不一致则不必写parameterType。比较旧的版本参数索引的写法为#{0},但是我使用的版本为3.4.写法则为#{arg0}
UserEntity getByIdStatus(int id, int status);
<select id="getByIdStatus" resultMap="userMap">
select * from user where id=#{arg0} and status=#{arg1}
</select>
当传递多个参数,还可以使用mybatis的@Param注解,给参数起别名,达到接收参数更加的清晰,而且不需要注意参数顺序的目的
UserEntity getByIdStatus(@Param(value = "xxxx") int id, @Param(value = "oooo")int status);
<select id="getByIdStatus" resultMap="userMap">
select * from user where id=#{xxxx} and status=#{oooo}
</select>
当传入的参数为集合的时候,参数的接收:
void removeByIds(List<Integer> ids);
<delete id="removeByIds" parameterType="java.util.List">
delete from user where id in
<foreach item="item" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</delete>
在没有mybatis中,参数传递使用map,首先是,parameterType设置为map类型。取值的话和对象传值是一样的,使用${key} 或者#{key}都可以,不过${}取值不安全,可能会有SQL注入的风险,所以一般建议使用#{}取值。判断map中是不是包含某个key,可以使用_parameter.containsKey('key') 来判断.如果map有值类型为对象的,则可以通过#{obj.attr}来获取属性值
UserEntity getByMap(Map<String, Object> map);
<select id="getByMap" parameterType="java.util.Map" resultMap="userMap">
select * from user
<where>
<if test="_parameter.containsKey('user')">
and name like '%' #{user.name} '%'
</if>
<if test="_parameter.containsKey('user')">
and id = ${user.id}
</if>
</where>
</select>