Mybatis使用@param注解四種情況解析
一、方法有多個(gè)參數(shù)
例如:
接口方法:
@Mapper
public interface UserMapper {
Integer insert(@Param("username") String username, @Param("address") String address);
}
對應(yīng)的xml:
<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
insert into user (username,address) values (#{username},#{address});
</insert>
原因:當(dāng)不使用 @Param 注解時(shí),mybatis 是不認(rèn)識(shí)哪個(gè)參數(shù)叫什么名字的,盡管在接口中定義了參數(shù)的名稱,mybatis仍然不認(rèn)識(shí)。這時(shí)mybatis將會(huì)以接口中參數(shù)定義的順序和SQL語句中的表達(dá)式進(jìn)行映射,這是默認(rèn)的。
二、方法參數(shù)要取別名
例如
@Mapper
public interface UserMapper {
Integer insert(@Param("username") String username, @Param("address") String address);
}
對應(yīng)的xml:
<insert id="insert" parameterType="org.javaboy.helloboot.bean.User">
insert into user (username,address) values (#{username},#{address});
</insert>
三、XML 中的 SQL 使用了 $ 拼接sql
$ 會(huì)有注入的問題,但是有的時(shí)候不得不使用 $ 符號(hào),例如要傳入列名或者表名的時(shí)候,這個(gè)時(shí)候必須要添加 @Param 注解
例如:
@Mapper
public interface UserMapper {
List<User> getAllUsers(@Param("order_by")String order_by);
}
對應(yīng)xml:
<select id="getAllUsers" resultType="org.javaboy.helloboot.bean.User">
select * from user
<if test="order_by!=null and order_by!=''">
order by ${order_by} desc
</if>
</select>
四、動(dòng)態(tài) SQL 中使用了參數(shù)作為變量
如果在動(dòng)態(tài) SQL 中使用參數(shù)作為變量,那么也需要 @Param 注解,即使你只有一個(gè)參數(shù)。例如如下方法:
@Mapper
public interface UserMapper {
List<User> getUserById(@Param("id")Integer id);
}
對應(yīng)xml:
<select id="getUserById" resultType="org.javaboy.helloboot.bean.User">
select * from user
<if test="id!=null">
where id=#{id}
</if>
</select>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringCloud解決Feign異步回調(diào)問題(SpringBoot+Async+Future實(shí)現(xiàn))
這篇文章主要介紹了SpringCloud解決Feign異步回調(diào)問題(SpringBoot+Async+Future實(shí)現(xiàn)),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
springboot項(xiàng)目開啟https協(xié)議的項(xiàng)目實(shí)現(xiàn)
本文主要介紹了springboot項(xiàng)目開啟https協(xié)議的項(xiàng)目實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
深入理解java異常處理機(jī)制的原理和開發(fā)應(yīng)用
Java異常處理機(jī)制在日常開發(fā)中應(yīng)用頻繁,本篇文章主要在基礎(chǔ)的使用方法上,更進(jìn)一步的,如何更加合理的使用異常機(jī)制,希望可以對各位朋友能有所幫助。2017-04-04
Intellij IDEA 關(guān)閉和開啟自動(dòng)更新的提示?
這篇文章主要介紹了Intellij IDEA 關(guān)閉和開啟自動(dòng)更新的提示操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
SpringBoot條件注解之@ConditionalOnClass等注解的使用場景分析
文章詳細(xì)介紹了SpringBoot中條件注解的體系,包括基本概念、@ConditionalOnClass等常用注解的工作原理和使用場景,文章還探討了條件注解的組合使用、實(shí)戰(zhàn)應(yīng)用以及最佳實(shí)踐,幫助開發(fā)者更好地理解和應(yīng)用條件注解,實(shí)現(xiàn)更靈活和智能的應(yīng)用配置,感興趣的朋友一起看看吧2025-03-03
SpringBoot之返回json數(shù)據(jù)的實(shí)現(xiàn)方法
這篇文章主要介紹了SpringBoot之返回json數(shù)據(jù)的實(shí)現(xiàn)方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12

