mybatis的一個重大好處是可寫動態的sql,否則我們還需要在代碼中判斷。這里說的動態sql不是指使用參數,而是指可以使用if,else,choose等流程控制關鍵字,實例可以參考官網。
關於mybatis的參數變量,一個重要的區別就是#{},${}。# 表示該語句會使用sql預編譯,其sql結構不會變,只會填入變量值。而$會用字符代替,然后編譯。典型的例子:
select * from student where name = #{name}; select * from student where name = ${name}; 如果name值為1 or 1 =1,則語句變為: select * from student where name = '1 or 1 =1'; select * from student where name = 1 or 1 =1;
可以看到,$符號會改變sql的語句結構,增加了or關鍵字,可能出現sql注入問題,#則不存在。那就應該盡量使用#{}, 那么是不是說${}就應該禁止呢?我們來看一下其他情況:
1.select * from student where name like '%#{name}%'; // 錯誤寫法 2.select * from student where name like '%${name}%';
1語句在預編譯是會變成:select * from student where name like '%’liyong’%',不符合sql語法,會報錯,而后面就不會,並且不會出現sql注入問題。
如果一定要用#,則可以使用mysql的單雙引號的間隔法:
select * from student where name like "%"#{name}"%"; // 字編譯后會進行字符串的拼接
select * from student_class_${id} where name= '小王子' // 必須使用$,組成一個完整的表名
下面來談一下第二個主題,關於@param注解的使用。這兩篇博文有很好的解釋。@Param的原理是將@Param注解的編碼封裝成了map,所以在使用Map參數據的接口中,不應該使用@param注解,但是其他情況應盡量使用@param注解,未使用則會報如下錯誤。
The error may involve defaultParameterMap ### The error occurred while setting parameters ### SQL: select * from news where news_abstract like %?% and item1 = ? ### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '%'abstract'% and item1 = 'dsdzfs'' at line 1
近期的數據庫和批量查詢寫法,讓我對mybatis中的mapper文件的寫法更加熟練了。
項目中使用mybatisplus,瞟了一眼,主要就是替代了mybatis中的sql語句,具體是怎么替代的,可以理解為用成語代替白話文,比如:
select * from student where name=“AA“; queryWrapper.eq("name",AA");// 第二句在一定的語以環境下可以翻譯成第一句話,且更具有結構化,出錯更少。
mybatisplus提供了AutoGenetor,用於快速生成controller,service,mapper等類和文件
queryWrapper.groupBy("CODE"); // group by會顯著降低性能,一個數據庫查詢就耗費13.2s,mybatis好用,但不要濫用

在mybatis中,參數主要分為單一類型: 比如int,string..., JavaBean對象,比如User,以及集合,List,Map等3個大類。一般來說,不建議將單一類型和JavaBean對象混用,會報錯,有這種需求時,可以將其放入Map中,組成符合類型。
參考博文:https://blog.csdn.net/lgc592519828/article/details/79749972?utm_source=blogkpcl1
參考博文:https://www.cnblogs.com/yysbolg/p/6768194.html
參考博文:https://www.cnblogs.com/fnlingnzb-learner/p/10566452.html