版权声明:本文为博主原创文章,无需授权即可转载,甚至无需保留以上版权声明,转载时请务必注明作者。
https://blog.csdn.net/weixin_43453386/article/details/84138942
MyBatis——》mapper&xml传递参数
一、多个参数传递
1、顺序传参法——》不建议使用:不直观,顺序调整容易出错
#{}:对应传入参数的顺序
1) DAO层
public User selectUser(String userName, Integer companyId);
2) XML层
<select id="selectUser" resultMap="ResultMap">
select *
from user
where 1=1
<if test="#{0} != null and #{0} != ''">
and user_name = #{0}
</if>
and company_id = #{1}
</select>
2、@Param注解传参法——》建议使用:直观
#{}:对应注解@Param括号里面修饰的名称
1) DAO层
public User selectUser(@Param("userName") String userName, Integer @Param("companyId") companyId);
2) XML层
<select id="selectUser" resultMap="ResultMap">
select *
from user
where 1=1
<if test="userName!= null and userName!= ''">
and user_name = #{userName}
</if>
and company_id = #{companyId}
</select>
3、Map传参法——》建议使用:不用一直修改传入参数
#{}:对应的是Map里面的key名称
1) DAO层
public User selectUser(Map<String, Object> params);
2) XML层
<select id="selectUser" parameterType="java.util.Map" resultMap="ResultMap">
select *
from user
where 1=1
<if test="userName!= null and userName!= ''">
and user_name = #{userName}
</if>
and company_id = #{companyId}
</select>
4、Java Bean传参法——》建议使用:直观,但需要实体类,需要扩展字段
#{}:对应的是User类里面的成员属性
1) DAO层
public User selectUser(User user);
2) XML层
<select id="selectUser" parameterType="com.test.User" resultMap="ResultMap">
select *
from user
where 1=1
<if test="userName!= null and userName!= ''">
and user_name = #{userName}
</if>
and company_id = #{companyId}
</select>
二、单个参数传递
1、单个参数
传入单个参数, 使用_parameter或#{0}
1) DAO层
public User selectUser(String userName);
2) XML层
## 第一种方式:
<select id="selectUser" resultMap="ResultMap">
select *
from user
where 1=1
<if test="_parameter!=null and _parameter!=''">
and user_name=#{_parameter}
</if>
</select>
## 第二种方式:
<select id="selectUser" resultMap="ResultMap">
select *
from user
where 1=1
<if test="#{0}!=null and #{0}!=''">
and user_name=#{0}
</if>
</select>