JAVA--Mybatis动态语句(3)

本文详细介绍MyBatis中基于XML配置的动态SQL语句使用方法,包括<if>、<where>、<foreach>标签的应用,以及如何通过这些标签根据传入参数条件进行查询,实现SQL语句的动态生成。

Mybatis基于XML配置的动态语句使用

根据传入参数条件,进行查询

1、标签,多场景时使用and

  <select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
		    select * from student where 1=1
	        <if test="name != null">
	            and name=#{name}
	        </if>
			<if test="条件">
			...
			</if>
		</select>
		<!-- 注:test属性中写的时对象的属性名 -->

2、<where>

当至少有一个if子元素的条件成立,sql才会插入“where”元素,并且会自动去除多余的and和or

  <select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
		    select * from student
			<where>
	            <if test="name != null">
	                name=#{name}
	            </if>
		    	<if test="条件">
		    	...AND ...
			    </if>
			</where>
		</select>

3、<foreach>遍历集合

<select id="selectStudentByCondition" resultType="com.lxb.domain.Student">
	    select * from student where 1=1
		<where>
            <if test="names != null and names.size()>0">
                <foreach collection="names" open="and name in (" close=")" item="name" sperator=",">
				    #{name}
				</foreach>
            </if>
		</where>
	</select>
	实现SQL语句:select column_name from table_name where id in(...)
	collection:代表要遍历的集合元素,代码中不使用#{}
	open:代表语句开始部分
	close:代表结束部分
	item:代表便利集合的每个元素,生成的变量名
	sperator:代表分隔符

抽取重复的sql语句
    定义:
          <sql id="defaultSql">
	           select * from student
		  </sql>
    使用:
	    <select ......>
		    <include refid="defaultSql"></include>
		/<select>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值