學習筆記 Mybatis(四) 動態sql

2022-09-13 19:51:10 字數 3561 閱讀 8548

動態sql——if標籤

以查詢product表為例:

1.product.xml配置檔案

使用模糊查詢的時候可能會用到不同的字段,如果查詢一次使用一條sql語句,會變得難以維護,就能使用mybatis的動態sql—-if標籤

;如果沒有傳入引數那麼就是查詢所有,這樣就可以一條語句應付多種情況。

select * from product_

where name like concat('%',#,'%')

if>

select>

2.test

// 查詢product使用模糊查詢

private

static

void

listproductbyname(sqlsession session)

}

動態sql——where標籤

1.修改product.xml配置檔案

當出現多條件查詢的時候不能愉快的直接使用

select * from product_ where name like concat(『%』,#,』%』) and price > #會出現name為空price不為空的語句錯誤;這時候就使用where標籤。

如果任何條件都不成立,那麼就在sql語句裡就不會出現where關鍵字

如果有任何條件成立,會自動去掉多出來的 and 或者 or。

select * from product_

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

if>

and price > #

if>

where>

select>

2.test

// 多條件查詢

private

static

void

listproductbynameandprice(sqlsession session)

}

動態sql——set標籤update product_

name=#,

price=#

set>

where

id=#

2.test

// 修改product

private

static

void

updateproductbyid(sqlsession session)

動態sql——trim標籤

trim 用來定製想要的功能,比如where標籤就可以用

prefix="where"

prefixoverrides="and|or">

trim>

替換

set標籤就可以用

prefix="set"

suffixoverrides=",">

trim>

替換。

id="listproductbyname"

resulttype="product">

select * from product_

prefix="where"

prefixoverrides="and|or">

test="name!=null">

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

if>

test="price!=null and price!=0">

and price > #

if>

trim>

select>

id="updateproduct"

parametertype="product">

update product_

prefix="set"

suffixoverrides=",">

test="name!=null">name=#,if>

test="price!=null">price=#if>

trim>

where id=#

update>

效果和where和set一樣。

動態sql——choose標籤

1.修改product.xml配置檔案

id="productlist"

resulttype="product">

select * from product_

test="name!=null">and name like concat('%',#,'%')when>

test="price!=null and price!=0">and price > #when>

and id>1

otherwise>

choose>

where>

select>

2.test

private

static

void

productlist(sqlsession session)

}

動態sql——foreach標籤

1.修改product.xml配置檔案

id="listproductforeach"

resulttype="product">

select * from product_

where id in

item="item"

index="index"

collection="list"

open="("

separator=","

close=")">

#foreach>

select>

2.test

private

static

void

productlistforeach(sqlsession session)

}

動態sql——bind標籤

1.修改product.xml配置檔案

id="listproductbind"

resulttype="product">

name="likename"

value="'%'+name+'%'" />

select * from product_ where name like #

select>

2.test

private

static

void

listproductbind(sqlsession session)

}

Mybatis筆記(四) 動態SQL

selbyaccinaccout resulttype log select from log where 1 1 上句沒有分號,因為要與下面的句子相連 ognl表示式,直接寫key或物件的屬性,不需要新增任何特字符號 if test accin null and accin and accin i...

Mybatis學習筆記 動態SQL

這片文章是對自己學習的總結。在mybatis的crud語句中,可以通過設定一些引數或者標籤,來讓我們寫sql語句時更加便利。sql元素的作用就是可以定義一條sql的一部分,然後以後的sql語句都可以直接引用它來減少 量。最常用的場景就是,我們在乙個dao層介面的配置檔案中進行各種各樣的查詢,但每次查...

Mybatis學習筆記之動態SQL揭秘

前言 動態sql是mybatis的乙個強大的特性,在使用jdbc運算元據時,如果查詢條件特別多,將條件串聯成sql字串是一件非常痛苦的事情,通常的解決方法使寫很多的if else條件語句去判斷和拼接,並確保不能忘了空格或在字段的最後省略逗號。mybatis使用一種強大的動態sql語言來改善這種情況 ...