SpringBoot整合Mybatis传参的几种方式

转自https://blog.csdn.net/irelia_/article/details/82347564

在SpringBoot整合Mybatis中,传递多个参数的方式和Spring整合Mybatis略微有点不同,下面主要总结三种常用的方式

一、顺序传参法
Mapper层:
传入需要的参数

public interface GoodsMapper {

public Goods selectBy(String name,int num);
}
1
2
3
4
Mapper.xml:
*使用这种方式,在SpringBoot中,参数占位符用#{arg0},#{arg1},#{arg…}

总结:这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

二、@Param注解传参法
Mapper层:

public interface GoodsMapper {

public Goods selectBy(@Param("name")String name,@Param("num")int num);

}
1
2
3
4
5
Mapper.xml:
*#{}里面的名称对应的是注解@Param括号里面修饰的名称。

<select id="selectBy" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from goods
where good_name=#{name} and good_num=#{num}
</select>
1
2
3
4
5
6
总结:这种方法在参数不多的情况还是比较直观的,推荐使用。

三、使用Map封装参数
Mapper层:
将要传入的多个参数放到Map集合

public interface GoodsMapper {

public Goods selectBy(Map map);
}
1
2
3
4
Mapper.xml:
*#{}里面的名称对应的是Map里面的key名称

<select id="selectBy" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from goods
where good_name=#{name} and good_num=#{num}
</select>
1
2
3
4
5
6
总结:这种方法适合传递多个参数,且参数易变能灵活传递的情况。

Service层:
带上要传入的参数

public interface GoodsService {

public Goods selectBy(String name,int num);
}
1
2
3
4
Service接口实现层:
封装Map集合:

@Override
public Goods selectBy(String name,int num) {
Map<String, String> map = new HashMap<String, String>();
map.put("name",name);
map.put("num",num+"");
return GoodsMapper.selectBy(map);
}
1
2
3
4
5
6
7
Controller层:
@RequestMapping("/selectBy.do")
@ResponseBody
public Goods selectBy(String name,int num) {

return goodsService.selectBy(name,num);
}
1

版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/ffaiss/p/10923467.html