1. 程式人生 > >動態SQL語句

動態SQL語句

使用 lis update語句 lose each 語法 oos 常用 sel

動態SQL語句


if標簽
例子:
<select id="listProduct" resultType="Product">
select * from product
<if test="name!=null">
where name like concat(‘%‘,#{name},‘%‘)
</if>
</select>

where標簽
<where>標簽會進行自動判斷
如果任何條件都不成立,那麽就在sql語句裏就不會出現where關鍵字
如果有任何條件成立,會自動去掉多出來的 and 或者 or。
例子:
<select id="listProduct" resultType="Product">
select * from product
<where>
<if test="name!=null">
and name like concat(‘%‘,#{name},‘%‘)
</if>
<if test="price!=null and price!=0">
and price > #{price}
</if>
</where>
</select>

set標簽
與where標簽類似,在update語句裏也會碰到多個字段相關的問題
如果任何條件都不成立,sql語句就不會出現set關鍵字
如果有任何條件成立,set標簽會自動去掉最後一個逗號
<update id="updateProduct" parameterType="Product" >
update product
<set>
<if test="name != null">name=#{name},</if>
<if test="price != null">price=#{price}</if>
</set>
where id=#{id}
</update>

trim標簽
trim 用來定制想要的功能
trim標簽可以替換where和set標簽:
prefixOverrides:前綴覆蓋(去掉多余的前綴)
<trim prefix="where" prefixOverrides="and |or ">
...
</trim>
suffixOverrides:後綴覆蓋(去掉多余的後綴)
<trim prefix="SET" suffixOverrides=",">
...
</trim>
例子:
<select id="listProduct" resultType="Product">
select * from product
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="name!=null">
and name like concat(‘%‘,#{name},‘%‘)
</if>
<if test="price!=null and price!=0">
and price > #{price}
</if>
</trim>
</select>

<update id="updateProduct" parameterType="Product" >
update product
<trim prefix="SET" suffixOverrides=",">
<if test="name != null">name=#{name},</if>
<if test="price != null">price=#{price}</if>

</trim>

where id=#{id}
</update>

choose標簽:(if else的效果)
Mybatis裏面沒有else標簽,但是可以使用when otherwise標簽來達到這樣的效果。
任何when條件成立,就進行條件查詢,否則就使用otherwise條件查詢
例子:
<select id="listProduct" resultType="Product">
SELECT * FROM product
<where>
<choose>
<when test="name != null">
and name like concat(‘%‘,#{name},‘%‘)
</when>
<when test="price !=null and price != 0">
and price > #{price}
</when>
<otherwise>
and id >1
</otherwise>
</choose>
</where>
</select>

foreach標簽
通常用於in 這樣的語法裏
例子:
<select id="listProduct" resultType="Product">
select * from product where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
調用的時候傳入一個list集合的對象為參數

bind標簽
就像是對傳入的參數做一次字符串拼接,方便後續使用
例子:模糊查詢,將傳入的name前後拼接上%
<select id="listProduct" resultType="Product">
<bind name="likename" value="‘%‘ + name + ‘%‘" />
select * from product where name like #{likename}
</select>

動態SQL語句