Mybatis动态sql用法

一、动态sql简介以及使用场景

在现实场景中,我们在进行物品选择的时候,通过不同的筛选条件 实现我们的目标选择。

同样在数据库进行有针对性对象的选择的时候,我们也可以根据sql语句的不同条件进行精准操作。即,根据不同标签组合sql语句。

实现方式: 映射配置文件xml;②注解;

常用的动态sql元素:

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

 二、映射配置文件xml--        动态sql中的元素标签

1、<if>标签

 if是 判断语句,用于单条件分支判断;在查询、删除、修改的时候会使用到. 

<select id="findStu" 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>

if 标签的 test 属性值是一个符合 OGNL 的表达式, 表达式可以是 true 或 false。如果为true就会被选择,如果是false,自动被省略不会被选择。

另外,if标签在条件不成立时,不会自动去掉where和add,所以在where后写1=1这个条件,让条件恒成立。

2、<choose>标签

<select id="findChoose" resultType="Student" parameterType="Student">
		select <include refid="ziduansql"></include> 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"
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis动态SQL是一种基于OGNL表达式的技术,可以在SQL语句实现一些逻辑判断。总体上,MyBatis动态SQL主要包含以下几类语句: 1. if语句:用于简单的条件判断。 2. choose语句(相当于Java语言的switch):包含when和otherwise子句,类似于JSTL的choose语句。 3. trim语句:在包含的内容上添加前缀或后缀,可以用于动态地拼接SQL语句。 4. where语句:主要用于简化SQL语句的where条件判断,能够智能地处理and和or,防止多余导致语法错误。 5. set语句:主要用于更新操作。 6. foreach语句:在实现MyBatis的in语句查询时特别有用。 以上是MyBatis动态SQL的几种主要用法,可以根据具体需求选择适合的方式来编写动态SQL语句。 MyBatis Dynamic SQL是一个与MyBatis配套的项目,它解决了MyBatis动态SQL方面的一些缺点,并提供了更灵活、强大的动态SQL功能。该项目可以帮助开发人员更方便地编写复杂的SQL语句,提高开发效率。你可以在官方文档了解更多关于MyBatis Dynamic SQL的信息。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [真正的Mybatis动态sqlMyBatis Dynamic SQL](https://blog.csdn.net/qq_36534560/article/details/119931287)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [mybatis动态sql及分页](https://blog.csdn.net/hjzhzhshhs/article/details/125241823)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值