mybatis中#{0}和#{arg0}的区别,xml中如何使用mapper接口的参数?

本文详细解析了MyBatis中参数传递的变化,从早期版本的位置传递方式到后期版本的改进,以及推荐使用的值传递方法,包括@Param注解的使用和集合参数的处理。

区别

在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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值