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是如何处理的。

关于Mybatis实现传入多个参数的四种方法详细讲解的文章就介绍至此,更多相关Mybatis传入多个参数内容请搜索编程宝库以前的文章,希望以后支持编程宝库

开窗函数能在每行的最后一行都显示聚合函数的结果,所以聚合函数可以用作开窗函数 聚合函数和开窗函数聚合函数是将多行变成一行,如果要显示其他列,必须将列加入group by开窗函数是将一行变成多行 ...