Mybatis 最強大的動態sql 標籤

2021-09-29 13:28:22 字數 1703 閱讀 9657

<

select id=

"findactivebloglike"

resulttype=

"blog"

>

select

*from blog

where

<

if test=

"state != null"

>

state =

#>

<

if test=

"title != null"

>

and title like

#>

<

if test=

"author != null and author.name != null"

>

and author_name like

#>

<

/select

>

如果這些條件沒有乙個能匹配上將會怎樣?最終這條 sql 會變成這樣:

select

*from blog

where

這會導致查詢失敗。如果僅僅第二個條件匹配又會怎樣?這條 sql 最終會是這樣:

select

*from blog

where

and title like 『yiibai.com』

這個查詢也會失敗。這個問題不能簡單的用條件句式來解決,如果你也曾經被迫這樣寫過,那麼你很可能從此以後都不想再這樣去寫了。

mybatis 有乙個簡單的處理,這在90%的情況下都會有用。而在不能使用的地方,你可以自定義處理方式來令其正常工作。一處簡單的修改就能得到想要的效果:

<

select id=

"findactivebloglike"

resulttype=

"blog"

>

select

*from blog

<

where

>

<

if test=

"state != null"

>

state =

#>

<

if test=

"title != null"

>

and title like

#>

<

if test=

"author != null and author.name != null"

>

and author_name like

#>

<

/where

>

<

/select

>

where 元素知道只有在乙個以上的if條件有值的情況下才去插入「where」子句。而且,若最後的內容是「and」或「or」開頭的,where 元素也知道如何將他們去除。

如果 where 元素沒有按正常套路出牌,我們還是可以通過自定義 trim 元素來定製我們想要的功能。比如,和 where 元素等價的自定義 trim 元素為:

"where" prefixoverrides=

"and |or "

>..

.<

/trim>

Mybatis的orderby引起的sql注入

sql中兩種傳引數的方式 這種是經過預編譯的,不會有sql注入 這種僅僅取變數的值,可以有sql注入 但是在orderby中之能用 用 會導致排序不生效。例如,傳入值為name時 用 select from student order by 會變成 select from student order...

最強大的Markdown編輯器

最強大的 你好!這是你第一次使用markdown編輯器所展示的歡迎頁。如果你想學習如何使用markdown編輯器,可以仔細閱讀這篇文章,了解一下markdown的基本語法知識。全新的介面設計,將會帶來全新的寫作體驗 在創作中心設定你喜愛的 高亮樣式,markdown將 片顯示選擇的高亮樣式進行展示 ...

功能最強大的編輯器 vi

vi是所有unix系統都會提供的螢幕編輯器,它提供了乙個視窗裝置,通過它可以編輯檔案。當然,對unix系統略有所知的人,或多或少都覺得vi超級難用,但vi是最基本的編輯器,所以希望讀者能好好把它學起來,以後在unix世界裡必將暢行無阻 游刃有餘,因為其他幾種文字處理器並非unix標準配備。說不定別人...