Mybatis动态 sql用法

本文详细介绍了Mybatis中的动态SQL用法,包括SqlMapper.xml文件中的动态SQL元素如<if>、<choose><when><otherwise>、<sql>、<include>、<where>、<set>、<trim>、<foreach>、<bind>,以及注解方式实现动态SQL,如脚本动态sql、@SelectProvider等。通过这些元素和注解,开发者可以灵活地根据条件拼接SQL语句,实现对数据库的精准操作。
摘要由CSDN通过智能技术生成

一、什么是动态sql

1、定义:

根据不同条件拼接sql语句,实现对数据库的精准操作

2、实现

sqlMapper.xml或注解

二、SqlMapper.xml文件中常用的动态SQL元素

<if>、<choose>、<when>、<otherwise>、<sql>、<include>、<where>、<set>、<trim>、<foreach>、<bind>

1、<if>

  • 用于条件判断
  • 当OGNL表达式为true时拼接在语句中,为false则会忽略被该标签包裹的内容
  • 多个条件时,每个标签内的条件前加add
  • 因为if标签在条件不成立时,不会自动去掉where和add,所以在where后写1=1,当以上情况发生时,条件衡成立
<select id="findStudent" resultType="student"
		parameterType="student">
		select * from student
		where 1=1
		<if test="ssex !=null">
			and ssex=#{ssex}
		</if>

		<if test="classid !=0">
			and classid=#{classid}
		</if>

	</select>

2、<choose><when><otherwise>

  • 多条件分支判断
  • when标签可以有多个,当when中的OGNL条件表达式成立时,则不走下一个when标签
  • oherwise类似defult,以上when条件都不成立时,就走otherwise中,当不写otherwise并且以上条件都不满足时,就是全查
    <select id="findStudentChoose" resultType="student"
    		parameterType="student">
    
    		select * from student where 1=1
    		<choose>
    			<when test="sname != null">and sname=#{sname}</when>
    			<when test="birthday !=null">and birthday=#{birthday}</when>
    			<when test="ssex !=null"> and ssex=#{ssex}</when>
    			<when test="classid !=0">and classid=#{classid}</when>
    		</choose>
    	</select>

3、<sql>

  • 在xml文件中,单独定义一个sql片段,封装sql片段
  • 可以封装sql
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值