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

在项目中定义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> 

总结

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容