下面给大家总结了以下几种多参数传递的方法。
方法1:顺序传参法
public User selectUser(String name, int deptId);
<select id="selectUser" resultMap="UserResultMap">
select * from user
where user_name = #{0} and dept_id = #{1}
</select>
#{}
里面的数字代表你传入参数的顺序。
这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。
方法2:@Param注解传参法
public User selectUser(@Param("userName") String name, int @Param("deptId") deptId);
<select id="selectUser" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>
#{}
里面的名称对应的是注解@Param括号里面修饰的名称。
这种方法在参数不多的情况还是比较直观的,推荐使用。
方法3:Map传参法
public User selectUser(Map<String, Object> params);
<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>
#{}
里面的名称对应的是Map里面的key名称。
这种方法适合传递多个参数,且参数易变能灵活传递的情况。
PS:
MyBatis传递map参数时,如果传递参数中没有对应的key值,在执行sql语句时默认取的是null
例如:map中没有put “name”这个key,在sql中使用#{name}时,默认赋值null
方法4:Java Bean传参法
public User selectUser(Map<String, Object> params);
<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
select * from user
where user_name = #{userName} and dept_id = #{deptId}
</select>
#{}
里面的名称对应的是User类里面的成员属性。
这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。
补充:
单个参数:
可以接受基本类型,对象类型,集合类型的值。这种情况MyBatis可直接使用这个参数,不需要经过任何处理。
<!-- 根据id查询数据表中的一条记录,并封装User对象 -->
<select id="selectById" resultType="com.softjx.model.User">
select t_id as id,t_username as username,t_password password from t_user where t_id=#{id}
</select>
<!--根据id查询数据表中的一条记录,使用了parameterType限定参数的类型,参数变量名可以随意定义,不受javabean中的属性控制-->
<select id="selectById1" parameterType="java.lang.Integer" resultType="com.softjx.model.User">
select t_id as id,t_username as username,t_password password from t_user where t_id=#{id1}
</select>
<!--或用${value}-->
<!--根据id查询数据表中的一条记录,使用了parameterType限定参数的类型,参数变量名固定是value,不可更换-->
<select id="selectById1" parameterType="java.lang.Integer" resultType="com.softjx.model.User">
select t_id as id,t_username as username,t_password password from t_user where t_id=${value}
</select>
ps:其中${value}中的value是固定的,不能换!固定的,不能换!固定的,不能换!
如果传输类型是简单类型,${ }中就只能使用value( 而#{ }中就随意了 )
固定是value的原因,请参阅:《深入了解MyBatis参数》
作者:架构之路
链接:https://www.jianshu.com/p/0ef856fcf938
作者:zheting
链接:https://www.jianshu.com/p/12581c13b37a
来源:简书