mybatis中的動態SQL

2021-09-26 04:38:53 字數 2367 閱讀 4502

動態sql的基本元素:

if:單條件分支判斷

choose,when,otherwise:多條件分支判斷

trim,set,where:用於處理sql拼裝問題

foreach:迴圈語句

bind:定義乙個上下文變數

test:用於判斷條件是否成立

if條件判斷語句:當角色名稱不為空時,根據角色名稱查詢物件

select role_no, role_name, note from t_role where 1=1

and role_name like concat('%', #, '%')

choose,when,otherwise多條件判斷語句:相當於if-else-else if

select role_no, role_name, note from t_role

where 1=1

and role_no = #

and role_name like concat('%', #, '%')

and note is not null

where語句和if語句拼接(當條件成立是,where後面直接跟and不報錯的原因,可以參考)

select role_no, role_name, note from t_role

and role_name like concat('%', #, '%')

and note like concat('%', #, '%')

當where元素裡面的條件成立時,才會加入where這個sql關鍵字到組裝的sql裡面。

使用trim刪掉特殊的元素,比如and,or

select role_no, role_name, note from t_role

and role_name like concat('%', #, '%')

trim元素意味著要去掉一些特殊的字元,當時prefix代表的是if語句的字首,當if語句成立時,才會加到語句的前面,而prefixoverrides代表的是當if語句成立時,去掉if語句中的and字元,suffixoverrides是去掉字尾,比如逗號。

使用set更新角色的資料,這樣我們就可以選擇更新的字段,而不用每個欄位都更新,而且set語句在遇到逗號時,會自動把對應的逗號去掉。

update t_role

role_name = #,

note = #

where role_no = #

使用foreach遍歷集合,它能夠很好的支援陣列和list,set幾口的集合,它往往用於sql中的in關鍵字。

select role_no, role_name, note from t_role where role_no in	#	

解釋一下,collection配置的rolenolist是傳遞進來的引數名稱,它可以是乙個陣列,list,set,等集合。

item配置的是迴圈中的當前的元素。

index配置的是當前元素在集合的位置下標。

open和close配置的是以什麼符號將這些集合元素包裝起來。

separator是各個元素的間隔符。

使用bind元素自定義乙個上下文變數,方便使用,在進行模糊查詢的時候,如果是mysql資料庫,常常用到的是乙個concat,它用』%'和引數相連,而在oracle資料庫中用||,這樣sql就需要提供兩種形式去實現,但是有了bind元素,就不必使用資料庫的語言,而是使用mybatis的動態sql即可完成。

select role_no, role_name, note from t_role

where role_name like #

這裡的_parameter代表的是傳遞進來的引數,它和萬用字元一起組成了pattern,然後就可以在select語句中使用這個變數進行模糊查詢了。無論是mysql還是oracle都可以使用這樣的語句,提高了**的移植性。

使用bind傳遞多個引數

首先定義介面方法

public listfindrole(@param("rolename") string rolename, @param("note") string note);
定義對映檔案

select role_no, role_name, note from t_role

where role_name like

# and note like #

使用多個條件進行模糊查詢。

mybatis中的動態sql

if元素用法 select id role name as rolename note from t role where id and role name like concat choose when othersize元素用法 這三個元素充當了switch語句 select role no,r...

mybatis動態sql中foreach標籤的使用

foreach標籤主要用於構建in條件,他可以在sql中對集合進行迭代。如下 delete from user where id in 我們假如說引數為 int ids 那麼列印之後的sql如下 delete form user where id in 1,2,3,4,5 釋義 collection...

mybatis動態sql中foreach標籤的使用

foreach標籤主要用於構建in條件,他可以在sql中對集合進行迭代。如下 delete from user where id in 我們假如說引數為 int ids 那麼列印之後的sql如下 delete form user where id in 1,2,3,4,5 釋義 collection...