Mybatis實現(xiàn)傳入多個參數(shù)的四種方法詳細(xì)講解
一、Mybatis四種傳遞多個參數(shù)的方式
XML文件或者注解中都通過#{}獲取參數(shù)的值,${}也可以,但是存在SQL注入問題。
1)參數(shù)索引
Mybatis會將參數(shù)放在map集合中,并以如下方式存儲數(shù)據(jù):
以param1, param2…為key,參數(shù)值為value。
多個參數(shù)可以使用類似于索引的方式傳值,比如#{param1}對應(yīng)第一個參數(shù),#{param2}對應(yīng)第二個參數(shù)…
1> Mapper方法:
User getUserByUserIdAndName(Long userId, String name);
2> XML文件內(nèi)容:
<select id="getUserByUserIdAndName" resultType="com.saint.vo.User">
select
id, name, age
from
tb_user
where
id = #{param1} and name = #{param2}
</select>
根據(jù)開發(fā)規(guī)范,這種方式很不推薦?。?/p>
如果參數(shù)個數(shù)比較少,并且不想使用Map、POJO的方式,可以使用參數(shù)名 替代 索引。
<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會將參數(shù)放在map集合中,除了以param1, param2..為key的方式存儲數(shù)據(jù)外,還會以如下方式存儲數(shù)據(jù):
以@Param注解的value屬性值為key,參數(shù)值為value。
1> Mapper方法:
User getUserById(@Param("id") Long id);2> XML文件內(nèi)容:
<select id="getUserById" parameterType="long" resultType="com.saint.vo.User">
select
id, name, age
from
tb_user
where
id = #{id}
</select>
控制臺日志輸出:

3)Map集合
Mybatis底層就是將入?yún)⑥D(zhuǎn)換成Map,入?yún)⒅苯觽鱉ap時,#{key}中的key就是Map中的key;
1> Mapper方法:
Message getMessageByMap(Map<String, Object> params);
2> XML文件內(nèi)容:
<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方法的調(diào)用:
Map<String, Object> params = new HashMap<>();
params.put("userId", 2L);
params.put("userName", "saint");
User user = userMapper.getUserByMap(params);
控制臺日志輸出:

4)POJO實體類
多個參數(shù)也可以用實體類封裝起來,此時對應(yīng)的key就是屬性名稱,注意POJO實體類中的字段一定要有g(shù)et方法。
1> Mapper方法:
List<User> getUserByUser(User user);
2> XML文件內(nèi)容:
<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方法的調(diào)用:
User userParam = new User();
userParam.setName("saint");
userParam.setId(2L);
List<User> user = userMapper.getUserByUser(userParam);
System.out.println("user = " + user);
控制臺日志輸出:

下一篇文章將針對這四種傳參方式,從源碼層面看一看MyBatis是如何處理的。
到此這篇關(guān)于Mybatis實現(xiàn)傳入多個參數(shù)的四種方法詳細(xì)講解的文章就介紹到這了,更多相關(guān)Mybatis傳入多個參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java 使用JDBC構(gòu)建簡單的數(shù)據(jù)訪問層實例詳解
以下是如何使用JDBC構(gòu)建一個數(shù)據(jù)訪問層,包括數(shù)據(jù)轉(zhuǎn)換(將從數(shù)據(jù)庫中查詢的數(shù)據(jù)封裝到對應(yīng)的對象中……),數(shù)據(jù)庫的建立,以及如何連接到數(shù)據(jù)庫,需要的朋友可以參考下2016-11-11
SpringBoot+slf4j線程池全鏈路調(diào)用日志跟蹤問題及解決思路(二)
本文主要給大家介紹如何實現(xiàn)子線程中的traceId日志跟蹤,本文通過封裝Callable為例給大家介紹的非常詳細(xì),需要的朋友一起看看吧2021-05-05

