動態sql語句
可以在xml檔案中新增條件配置來動態拼接,呼叫sql語句
ibatis使用的ongl表示式有四種元素
if choose
trim
foreach
if
<select
id=」findactivebloglike」
parametertype=」blog」
resulttype=」blog」
>
select * from blog where state = 『active』
<
iftest=」title != null」>
and title like #
if>
<
iftest=」author != null && author.name != null」>
and title like #
if>
select
>
choose,when,otherwise
<select
id=」findactivebloglike」
parametertype=」blog」
resulttype=」blog」
>
select * from blog where state = 『active』
<
choose
>
<
when
test=」title != null」>
and title like #
when
>
<
when
test=」author != null && author.name != null」>
and title like #
when
>
<
otherwise
>
and featured = 1
otherwise
>
choose
>
select
>
trim,where,set
where標籤可以動態加上where關鍵字:
<
select
id=」findactivebloglike」
parametertype=」blog」
resulttype=」blog」
>
select * from blog
<
where
>
<
iftest=」state != null」>
state = #
if>
<
iftest=」title != null」>
and title like #
if>
<
iftest=」author != null && author.name != null」>
and title like #
if>
where
>
select
>
這裡也可以自定義trim元素來控制where等關鍵字,下面的trim配置等價於where標籤
<trim
prefix="where"
prefixoverrides="and |or "
>
…trim
>
這裡trim標籤文件上敘述的很模糊,大概意思是如果trim內的字元帶有字首「and 」或者「or 」那麼去掉trim整段字元前面的where,否則新增where。
來看update語句中:
<update
id="updateauthorifnecessary"
parametertype="domain.blog.author"
>
update author
<
set>
<
iftest="username != null"
>username=#,if
>
<
iftest="password != null"
>password=#,if
>
<
iftest="email != null"
>email=#,if
>
<
iftest="bio != null"
>bio=#if
>
set>
where id=#
update
>
set標籤等價的trim標籤配置為
<trim
prefix="set"
suffixoverrides=","
>
…trim
>
這裡的trim標籤原文敘述的很模糊,大概意思是trim中的字元帶有字尾,的話那麼就去掉trim整段字元前的set,否則新增set
foreach
<select
id="selectpostin"
resulttype="domain.blog.post"
>
select *
from post p
where id in
<
foreach
item="item"
index="index"
collection="list"
open="("
separator=","
close=")"
>
#foreach
>
select
>
基本能明白foreach標籤的作用了:
item說明了集合內每乙個元素的值,並在下面的sql中使用# 來引用這個值
index說明了集合內每乙個元素的下標,並在下面的sql中使用# 來引用這個值
collection說明了集合元素的型別
open是指轉換後前面新增(
separator表示每個集合元素之間以「,」分隔
close在轉換後最後新增)。
iBATIS 3 試用手記三
前兩篇手記重點說了下ibatis 3的查詢功能,因為這是它改動最大的地方。這篇手記就來說下ibatis在persistance方面的改進。ibatis 3依然提供了標籤對資料庫進行持久化操作。首先來看insert操作 select seq nn mstr id.nextval from dual i...
ibatis3 因為ognl解析慢,導致效能下降
ibatis3的sql語句寫在xml裡,ibatis3使用了ognl解析器。1 當sql裡有多個時,大概有30個吧,明顯感覺速度慢下 例子update a a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a...
iBatis的學習筆記
官網 環境搭建 student.xml實體類對映檔案 別名select from student select sid,sname,score,major,birth from student where sid sid insert into student sid,sname,major,sco...