MyBatis框架 动态SQL

动态SQL

根据不同的条件需要执行不同的sql命令,动态生成相应的SQL语句

if

<if test=" "> and/or 表达式</if>
test属性使用OGNL表达式,直接写key或对象属性进行逻辑判断

where

<where>标签中若内容第一个是and,则会去掉and
若where内部条件都不成立,则不会生成where
<where> <if test=" "> and/or 表达式</if></where>
例:
接口方法:List<Commodity> selWhere(Commodity com);

<select id="selComm" resultType="Commodity">
  	SELECT * FROM commodity
  	<where>
   		<if test="price != null">
    			and price > #{price}
   		</if>
   		<if test="salenum != null">
    			and salenum > #{salenum}
   		</if>
  	</where>
 </select>
choose、when、otherwise

可以在where标签中进行选择,只执行一个条件
<where> <choose><when test=" "> and/or 条件</when> </choose></where>
例:
接口方法: List<Commodity> selWhen(@Param(“pr”) int price, @Param(“ty”) String type);

<!-- 测试choose、when及otherwise -->
<select id="selWhen" resultType="Commodity">
  	SELECT * FROM commodity
  	<where>
   		<choose>
    			<when test="pr != null and pr != 0">
     				and price = #{pr}
    			</when>
    			<when test="ty != null and ty!='' ">
     				and type = #{ty}
    			</when>
    			<otherwise>
     				price > 10
    			</otherwise>
   		</choose>
  	</where>
</select>
set

修改SQL中update语句中的set从句
去掉最后一个逗号
Ps:一般在<set>中第一行加入一个id=#{id},
防止set不生成表达式,导致出错
例:
接口方法:void upSet(Commodity com);

<!-- 测试set -->
<update id="upSet">
  	UPDATE commodity 
  	<set>
   		name = #{name},
   		<if test="price != null and price != 0">
    			price = #{price},
   		</if>
  	</set>
  	where name = #{name}
</update>
trim

属性:
prefix="“内容之前加
prefixOverrides=”“内容之前去掉
suffix=”“内容之后加
suffixOverrides=”"内容之后去掉
Ps:内容处理之后存在空格

bind

可以对传入的参数进行处理,再加入sql语句
如:<bind name=“money” value="’$’+money"/>即将100变为$100
Ps:可用于添加%进行模糊查询
例:
接口方法: List<Commodity> selTrim(String name);

<!-- 测试 trim-->
<select id="selTrim" resultType="commodity">
  	SELECT * FROM commodity
  	<where>
   		<if test="name != null">
    			<bind name="nameChange" value="'%'+name"/>
      			name like #{nameChange}
   		</if>
  	</where>
</select>
foreach

循环遍历容器,提取参数,一般用于IN查询或批量新增
还可添加分隔符
如:<foreach collection=" " item=“a” open="(" close=" )" separator=",">#{a}</foreach>
结果:(a1,a2,a3…)
例:
接口方法: List<Commodity> selForeach(@Param(“list”) List myList);

<!-- 测试foreach -->
<select id="selForeach" resultType="Commodity">
  	SELECT * FROM commodity WHERE price IN
  	<foreach collection="list" item="a" open="(" close=")" separator=",">
   		#{a}
  	</foreach>
 </select>

Ps:Mybatis中<forrach>效率较低
如果此处希望批量新增,则openSession()必须指定ExecutorType.BATCH

sql

<sql id=""> </sql>
定义一个sql片段,可在sql语句中引用
<include refid=“id号”/>
一般用于多表联合查询时,将大量的列名封装为一个片段

发布了82 篇原创文章 · 获赞 1 · 访问量 1458

猜你喜欢

转载自blog.csdn.net/qq_41891805/article/details/105037877