MyBatis3(动态SQL)

四.动态SQL

动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句. 主要是 where 部分发生变化
动态sql的实现, 使用的是mybatis提供的标签 , <if> <where> <foreach>
1.if 标签
1.<if>标签
<if>是判断条件的, 
	语法 <if test="判断java对象的属性值">
			部分sql语句
		</if>
		
	<!-- if
        <if test="使用参数java对象的属性值作为判断条件 , 语法 : 属性值==XXX值等等">

        </if>
        可能出现语法错误(多余的or或and)
     -->
    <select id="selectUserIf01" resultType="com.dsm.pojo.User">
        select * from user where 
        <if test="id > 3">
            id = #{id}
        </if>
        <if test="name !=null and name != ''">
            and name = #{name}
        </if>
    </select>
2.where标签
<where> 用来包含 多个<if>的, 当多个if有一个成立, <where>会自动增加一个where关键字, 并去掉 if 多余的and , or等


    <!-- where:
        <where> <if><if>...</where>
        内部有if成立才会自动在sql语句中加上一个where
        去掉多余的or and等等(避免出现语法错误)
    -->
    <select id="selectUserWhere" resultType="com.dsm.pojo.User">
        select * from user
        <where>
            <if test="id > 3">
                id = #{id}
            </if>
            <if test="name !=null and name != ''">
                and name = #{name}
            </if>
        </where>
    </select>
3.foreach标签
<foreach> 用于循环java中的数组,list集合的. 主要用在sql的in语句中.
	例如:查id为 1, 2, 3的
	select * from user where id in (1,2,3)
	现在1,2,3放在了数组或集合中使用<foreach>遍历到sql语句中
	
<foreach collection="" item="" open="" close="" separator="">
            #{XXX}
</foreach>
collection : 表示接口中的方法参数的类型,数组(array),List集合(list)
item : 自定义成员变量
open : 循环开始时的字符
close : 循环结束时的字符
separator : 集合成员之间的分隔符

	<!--
        foreach用法一(集合里面是数值)
     -->
    <select id="selectUserForeach01" resultType="com.dsm.pojo.User">
        select * from user where id in
        <foreach collection="list" item="listId" open="(" close=")" separator=",">
            #{listId}
        </foreach>
    </select>

    <!-- foreach用法二(集合里面是对象) -->
    <select id="selectUserForeach02" resultType="com.dsm.pojo.User">
        select * from user where id in
        <foreach collection="list" item="user" open="(" close=")" separator=",">
            #{user.id}
        </foreach>
    </select>
4.代码片段(实现代码复用)
1.先使用
	<sql id="自定义名称(唯一)"> 
		sql语句, 表名, 字段名等
	</sql>
2.在使用(插入sql语句的片段)
	<include refid="id的值"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值