美文网首页springbootJava web
Mybatis如何传递多个不同类型的参数

Mybatis如何传递多个不同类型的参数

作者: 勿念及时雨 | 来源:发表于2021-03-17 16:48 被阅读0次

在项目中定义Mapper方法时,有时可能会传多个不同类型的参数,比如像下面这个Mapper方法,这个时候应该如何进行配置呢?

List<String> findUserRole(Integer userId, String roleName);

方法一

不设置parameterType参数,直接使用#{index}来指定参数,索引从0开始。

<select id="findUserRole" resultType="string">
  select * from user_role where user_id= #{0} and role_name= #{1}  
</select>

方法二

使用@Param注解进行指定,推荐使用。
Mapper方法

List<String> findUserRole(@Param("userId") Integer userId, 
                          @Param("roleName") String roleName);

SQL配置文件

<select id="findUserRole" resultType="string">
  select * from user_role where user_id= #{userId} and role_name= #{roleName}  
</select>

方法三

使用Map进行封装,Map中的key的值就是参数的名称。
Mapper方法

List<String> findUserRole(HashMap<String,Object> paramMap);

SQL配置文件

<select id="findUserRole" resultType="string" parameterType="hashmap">
  select * from user_role where user_id= #{userId} and role_name= #{roleName}  
</select>

方法四

使用List封装,在SQL配置文件中使用foreach遍历参数。
Mapper方法

List<String> findUserRole(List<String> paramList);

SQL配置文件

<select id="findUserRole" resultType="string">
  select * from user_role where user_id in
  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
    #{item}  
  </foreach>  
</select> 

总结

方法三和方法四资源消耗远大于方法一和方法二,一般推荐使用方法一和方法二。

相关文章

网友评论

    本文标题:Mybatis如何传递多个不同类型的参数

    本文链接:https://www.haomeiwen.com/subject/yrjecltx.html