1、select查詢
簡單的select類似如下:
<select
id="findbyid"
resultmap
="studentresult"
parametertype
="integer"
>
select * from t_student where id = #
select
>
1)if(常用於各種查詢的條件判斷部分)
<select
id="searchstudents"
parametertype
="map"
resultmap
="studentresult"
>
select * from t_student
where gradeid = #
<
if test
="name != null"
>
and name like #
if>
<
if test
="age != null"
>
and age = #
if>
select
>
結合where標籤使用如下:
<select
id="searchstudents3"
parametertype
="map"
resultmap
="studentresult"
>
select * from t_student
<
where
>
<
if test
="gradeid != null"
>
gradeid = #
if>
<
if test
="name != null"
>
and name like #
if>
<
if test
="age != null"
>
and age = #
if>
where
>
select
>
2)choose(同if..else..類似)
<select
id="searchstudents2"
parametertype
="map"
resultmap
="studentresult"
>
select * from t_student
<
choose
>
<
when
test
="searchby=='gradeid'"
>
where gradeid = #
when
>
<
when
test
="searchby=='name'"
>
where name like #
when
>
<
otherwise
>
where age = #
otherwise
>
choose
>
select
>
3)trim
<select
id="searchstudents4"
parametertype
="map"
resultmap
="studentresult"
>
select * from t_student
<
trim
prefix
="where"
prefixoverrides
="and|or"
>
<
if test
="gradeid != null"
>
gradeid = #
if>
<
if test
="name != null"
>
and name like #
if>
<
if test
="age != null"
>
and age = #
if>
trim
>
select
>
prefix前置,prefixoverrides前置覆蓋,簡單理解為:trim子句中最前面的and或者or用where替換。
4)foreach
<select
id="searchstudents5"
parametertype
="map"
resultmap
="studentresult"
>
select * from t_student
<
if test
="gradeids != null"
>
<
where
>
gradeid in
<
foreach
collection
="gradeids"
item
="gradeid"
open
="("
close
=")"
separator
=","
>
#
foreach
>
where
>
if>
select
>
collections即陣列集合,可以是list型別,如arraylist等,open指定左側拼接方式,close指定右側,separator指定分隔符,這裡拼接後為括號括起來逗號隔開的字串,從而用於in查詢。
2、update
<update
id="updatestudent"
parametertype
="student"
>
update t_student
<
set>
<
if test
="name != null"
>
name = #,
if>
<
if test
="age != null"
>
age = #
if>
set>
where id = #
update
>
<update
id="update"
parametertype
="student"
>
update t_student set name =
#,age = # where id = #
update
>
3、delete
<delete
id="delete"
parametertype
="integer"
>
delete from t_student where id = #
delete
>
4、insert
<
insert
id="add"
parametertype
="student"
>
insert into t_student(id,name,age) values(null,#,#)
insert
>
(七)mybatis學習之動態SQL
mybatis的核心是對sql語句進行靈活的操作,通過表示式進行判斷,對sql進行靈活拼接 組裝。動態sql包括 if choose when,otherwise where set trim foreach sql片段 if標籤比較簡單,這裡記錄一下文件內容的例子,通過看例子,就清楚的知道if是如...
Mybatis學習筆記之動態SQL揭秘
前言 動態sql是mybatis的乙個強大的特性,在使用jdbc運算元據時,如果查詢條件特別多,將條件串聯成sql字串是一件非常痛苦的事情,通常的解決方法使寫很多的if else條件語句去判斷和拼接,並確保不能忘了空格或在字段的最後省略逗號。mybatis使用一種強大的動態sql語言來改善這種情況 ...
mybatis動態SQL之if標籤
我們根據實體類的不同取值,使用不同的 sql 語句來進行查詢。比如在 id 如果不為空時可以根據 id 查詢,如果 username 不同空時還要加入使用者名稱作為條件。這種情況在我們的多條件組合查詢中經常會碰到。根據使用者資訊,查詢使用者列表 param user return listfindb...