myBatis动态SQL

本文详细介绍了MyBatis中if标签和where标签的用法,针对动态SQL拼接时可能出现的问题,如空值导致的SQL错误,提出了两种解决方案:添加1=1条件和使用where标签。通过示例展示了如何在查询员工信息时根据条件动态添加查询条件,确保SQL语句的正确性。
摘要由CSDN通过智能技术生成
  • if
  • choose(when, otherwise)
  • trim(where, set)
  • foreach
1. if| 查询员工,那个携带了字段查询条件就带上这个字段的值
<!-- public Lsit<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="">
	select * from tab_employee
	where 
	<!-- test,判断表达式(OGNL)
		c:if   test
		从参数中取值进行判断
		-->
	<if test="id!=null">
	id = #{id}
	</if>
	<if test="last_name!=null and last_name.trim()=''">
	 and last_name like #{lastName}
	</if>
	<!--ognl会进行字符串与数字的转换判断 "0"==0-->
	<if test="gender==0 or gender==1">
	and gender=#{gender}
	</if>

当id == null 时, sql 拼接会变成, where and … 。 会报错

第一种解决办法, 在后面加上1=1, where 1=1 and …
第二种使用where标签来包扩所有的查询条件, mybatis就会将where标签中拼装的sql, 多出来的and或or去掉 //where自会去掉第一个多出来的and或者or

2. where
<!-- public Lsit<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="">
	select * from tab_employee
	<where> 
	<!-- test,判断表达式(OGNL)
		c:if   test
		从参数中取值进行判断
		-->
	<if test="id!=null">
	id = #{id}
	</if>
	<if test="last_name!=null and last_name.trim()=''">
	 and last_name like #{lastName}
	</if>
	<!--ognl会进行字符串与数字的转换判断 "0"==0-->
	<if test="gender==0 or gender==1">
	and gender=#{gender}
	</if>
	</where>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值