mybatis动态sql

简单总结一下。
1、if。类似于java中if。test中写条件

select * from user
	where 1=1
		<if test="sex !=null and sex!=''">
			and sex =#{sex}
		</if>
		<if test="username !=null and username !=''">
			and username like '%${username}%'
		</if>

2、where。mysql中的添加查询条件。可以自动去除一个andor关键词

select * from user
	<where>
			<if test="sex !=null and sex!=''">
				and sex =#{sex}
			</if>
			<if test="username !=null and username !=''">
				and username like '%${username}%'
			</if>
	</where>

3、foreach。循环。
separator:遍历对象之间需要拼接的字符串
open:拼接开头部分。
close:拼接结束部分。
collection:循环的集合
item:每次遍历生成的对象

select * from user
		<where>
			id in
			<foreach collection="idList" separator="," open="(" close=")"
				item="id">
				#{id}
			</foreach>
		</where>
		<!-- 最后输出形式    
		select * from user WHERE id in ( ? , ? , ? ) 
		-->

4、sql。sql片段
有时候一个判断或其他sql多次用到,为了增加代码重用行,简化代码。添加一个代码片段。其他地方可以直接调用。

<sql id="sexV">
		<if test="sex !=null and sex!=''">
			and sex =#{sex}
		</if>
</sql>

select * from user
	<where>
		<include refid="sexV"></include>
		<if test="username !=null and username !=''">
			and username like '%${username}%'
		</if>
	</where>

5、choose(when,otherwise) 语句
有时候我们只想用很多条件中的一个,满足一个条件即可。类似于java的switch。

select * from user
	<where>
			<choose>
				<when test="username !=null and username !=''">
					and username like '%${username}%'
				</when>
				<when test="sex !=null and sex!=''">
					and sex =#{sex}
				</when>
				<otherwise>
					and id=#{id}
				</otherwise>
			</choose>
	</where>

6、set 语句
在做更新操作时。

update user
<set>
      <if test="username != null and username != ''">
           u.username = #{username},
       </if>
       <if test="sex != null and sex != ''">
           u.sex = #{sex}
       </if>
</set>
where id=#{id}

7、trim(where,set)标签
prefix:前缀      
prefixoverride:去掉第一个and或者是or。
suffix:后缀  
suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

select * from user
		<!--  
			<where>
			<include refid="sexV"></include>
			<if test="username !=null and username !=''">
				and username like '%${username}%'

			</if>
		
		</where>
		-->
		<trim  prefix="where"  prefixOverrides="and | or ">
		<include refid="sexV"></include>
			<if test="username !=null and username !=''">
				and username like '%${username}%'

			</if>
		</trim>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值