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

版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM