Mybatis传入多个参数的四种方式

一、Mybatis四种传递多个参数的方式

XML文件或者注解中都通过#{}获取参数的值,${}也可以,但是存在SQL注入问题。

1)参数索引

Mybatis会将参数放在map集合中,并以如下方式存储数据:

  • 以param1, param2…为key,参数值为value。

多个参数可以使用类似于索引的方式传值,比如#{param1}对应第一个参数,#{param2}对应第二个参数…

1> Mapper方法:

User getUserByUserIdAndName(Long userId, String name);

2> XML文件内容:

<select id="getUserByUserIdAndName" resultType="com.saint.vo.User">
    select
    id, name, age
    from
    tb_user
    where
    id = #{param1} and name = #{param2}
</select>

根据开发规范,这种方式很不推荐!!

  • 如果参数个数比较少,并且不想使用Map、POJO的方式,可以使用参数名 替代 索引。
<select id="getUserByUserIdAndName" resultType="com.saint.vo.User">
    select
    id, name, age
    from
    tb_user
    where
    id = #{userId} and name = #{name}
</select>

控制台日志输出:

在这里插入图片描述

2)@Param

Mybatis会将参数放在map集合中,除了以param1, param2..为key的方式存储数据外,还会以如下方式存储数据:

  • @Param注解的value属性值为key,参数值为value。

1> Mapper方法:

User getUserById(@Param("id") Long id);

2> XML文件内容:

<select id="getUserById" parameterType="long" resultType="com.saint.vo.User">
    select
        id, name, age
    from
        tb_user
    where
        id = #{id}
</select>

控制台日志输出:

在这里插入图片描述

3)Map集合

Mybatis底层就是将入参转换成Map,入参直接传Map时,#{key}中的key就是Map中的key;

1> Mapper方法:

Message getMessageByMap(Map<String, Object> params);

2> XML文件内容:

<select id="getMessageByMap" parameterType="map" resultType="com.saint.vo.Message">
    select
        id, msg_id, status, content, deleted, create_time, update_time
    from
        tb_message
    where
        id = #{id} and msg_id = #{msgId}
</select>

3> Mapper方法的调用:

Map<String, Object> params = new HashMap<>();
params.put("userId", 2L);
params.put("userName", "saint");
User user = userMapper.getUserByMap(params);

控制台日志输出:

在这里插入图片描述

4)POJO实体类

多个参数也可以用实体类封装起来,此时对应的key就是属性名称,注意POJO实体类中的字段一定要有get方法。

1> Mapper方法:

List<User> getUserByUser(User user);

2> XML文件内容:

<select id="getUserByUser" parameterType="com.saint.vo.User" resultType="com.saint.vo.User">
    select id, name, age
    from tb_user
    where 1=1
    <if test="id != null">
        and id = #{id}
    </if>
    <if test="name != null and name != ''">
        and name = #{name}
    </if>
    <if test="age != null">
        and age = #{age}
    </if>
</select>

3> Mapper方法的调用:

User userParam = new User();
userParam.setName("saint");
userParam.setId(2L);
List<User> user = userMapper.getUserByUser(userParam);
System.out.println("user = " + user);

控制台日志输出:

在这里插入图片描述

二、后续

下一篇文章将针对这四种传参方式,从源码层面看一看MyBatis是如何处理的。

猜你喜欢

转载自blog.csdn.net/Saintmm/article/details/128725686