区别
在mybatis早的版本(3.4.2之前)中,如果Mapper接口中的方法的参数上没有使用注解指定参数名@Param("")
,则可以按照参数的顺序,在xml文件中使用#{0}、#{1}、#{2}、#{3}…来获取到参数中的数据。
举例:
Mapper接口:
User getUserBys(int id,String name);
xml文件:
<select id="getUserBys" resultType="com.model.User">
select * from user where id = #{0} and name=#{1}
</select>
在mybatis后来的版本(3.4.2之后)中,使用arg0
来代替0
。
举例
Mapper接口:
User getUserBys(int id,String name);
xml文件:
<select id="getUserBys" resultType="com.model.User">
select * from user where id = #{arg0} and name=#{arg1}
</select>
注意:上面两种方法都属于位置传递
建议
为了避免不必要的麻烦,我们可以使用值传递的方式,在Mapper类中使用@Param("")
注解,xml中使用的话,直接通过名字找到。
Mapper接口:
User getUserBys(@Param("id") int id,@Param("name") String name);
xml文件:
<select id="getUserBys" resultType="com.model.User">
select * from user where id = #{id} and name=#{name}
</select>
扩展
对于集合来说,mybatis有默认的参数名字,比如List
类型的可以通过list
获取、数组类型的可以通过array
获取。举个例子,接口的参数名为idList
,在xml中要用到这个参数,可以使用list
获取。
Mapper接口:
public List<User> findByIdList(List<Integer> idList);
xml:
<select id="findByIdList" resultType="com.example.bean.User">
SELECT id, name, password, address, enable
FROM user
<where>
<if test="list!= null and list.size() > 0">
id IN
<foreach collection="list" item="ietm" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</select>