什么是動態SQL:動態SQL就是根據不同的條件生成不同的SQL語句
基本流程
1,數據庫準備一張表
2,導包
3,編寫核心配置文件
4,編寫實體類
5,編寫實體類對應的Mapper和Mapper.xml文件
6,在核心配置文件中注冊Mapper.xml
7,測試
開啟自動駝峰命名規則映射
1
2
|
<!--開啟駝峰命名映射--> < setting name = "mapUnderscoreToCamelCase" value = "true" /> |
即在數據庫中為create_time對應Java實體類屬性createTime
IF,Where
1
2
3
4
5
6
7
8
9
10
11
|
< select id = "queryListIf" parameterType = "map" resultType = "Blog" > select * from blog < where > < if test = "title != null" > title = #{title} </ if > < if test = "author != null" > and author = #{author} </ if > </ where > </ select > |
Where的作用:當至少有一個滿足條件時添加Where,且會判斷后面加的第一條語句,若是and開頭,則會自動將這個and刪除
本質上還是在拼接SQL,上述當沒有滿足條件時查詢blog表中的所有,當滿足條件時,則拼接SQL
Set
1
2
3
4
5
6
7
8
9
10
11
12
|
< update id = "updateBlog" parameterType = "map" > update blog < set > < if test = "title != null" > title = #{title}, </ if > < if test = "author != null" > author = #{author} </ if > </ set > where id = #{id} </ update > |
Set的作用:至少有一個滿足條件時添加Set,且會判斷后面加的最后的語句,若是",“結尾,則會自動將這個”,"刪除
Choose(when,otherwise)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
< select id = "queryNoLimit" parameterType = "map" resultType = "Blog" > select * from blog < where > < choose > < when test = "title != null" > title = #{title} </ when > < when test = "author != null" > and author = #{author} </ when > < otherwise > and `view` = #{view} </ otherwise > </ choose > </ where > </ select > |
choose(when,otherwise)類似與Java中的switch(case,default),choose進入選擇,when當什么什么時,進行條件判斷,若滿足條件,則執行條件中的內容,后面的when,otherwise將不再執行,otherwise當所有when都不滿足條件時執行
ForEach
1
2
3
4
5
6
7
8
|
< select id = "queryBlogById" parameterType = "map" resultType = "blog" > select * from blog < where > < foreach collection = "ids" item = "id" open = "(" close = ")" separator = "or" > id = #{id} </ foreach > </ where > </ select > |
上述為,一個集合ids存儲id的內容,根據這個集合查詢所包含的id,open為開始,close為結束,separator為分隔符
才用map.put(“ids”,list)的方式導入集合
建議:現在Mysql中寫出完整的sql,再對應的去修改即可
SQL片段
將一些功能的部分抽取出來方便復用
使用SQL標簽抽取公共的部分
1
2
3
4
5
6
7
8
|
< sql id = "titleAuthor" > < if test = "title != null" > title = #{title} </ if > < if test = "author != null" > and author = #{author} </ if > </ sql > |
在需要的地方使用include標簽引用即可
1
2
3
4
5
6
|
< select id = "queryListIf" parameterType = "map" resultType = "Blog" > select * from blog < where > < include refid = "titleAuthor" ></ include > </ where > </ select > |
注意事項:
1.最好基于單表來定義SQL片段
2.不要存在where標簽
總結
所謂的動態SQL就是在拼接SQL語句,我們只要保證SQL的正確性,按照SQL的格式去排列組合就可以了
到此這篇關于Mybatis動態SQL的示例代碼的文章就介紹到這了,更多相關Mybatis動態SQL內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/shuati2000/article/details/120964434