注意 Mybatis 中,拼接模糊查询的用法 #,是将传入的值当作字符串的形式。因此拼接的时候 #{userName} 默认自带引号。 例如:
直接转为
。userName直接转为′zhen′。,是将传入的数据直接显示生成sql语句。java
这里先给你们看一下结论spring
Oracle 中,拼接模糊查询的正确写法sql
SELECT A.USER_ID, A.USER_NAME FROM T_USER A AND A.USER_NAME like concat(concat('%','w'),'%') 或者 AND A.USER_NAME like '%' || 'w' || '%'
Mybatis 中,拼接模糊查询的正确写法express
<select id="selectByName" resultMap="BaseResultMap"> SELECT A.USER_ID, A.USER_NAME FROM T_USER A <if test="userName != null"> AND A.USER_NAME like '%' || #{userName} || '%' </if> 或者 <if test="userName != null"> AND A.USER_NAME like concat(concat('%','${userName}'),'%') </if> </select>
#,是将传入的值当作字符串的形式。因此拼接的时候 #{userName} 默认自带引号。 例如: ${userName} 直接转为 'zhen'。 $,是将传入的数据直接显示生成sql语句。因此拼接的时候 ${userName} 没有默认引号。 例如:${userName} 直接转为 zhen 。
刚开始写的时候一直报错,报错信息是这样的:apache
"message": "Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='userName', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: 无效的列索引",
个人写法是这样的:性能优化
<if test="userName != null"> -- AND A.USER_NAME like CONCAT('%','#{userName}','%') AND A.USER_NAME = #{userName} </if> <!-- <if test="userType != null"> AND A.USER_TYPE = #{userType} </if> <if test="mobilePhoneNo != null"> AND A.MOBILE_PHONE_NO like CONCAT('%','#{mobilePhoneNo}','%') </if> <if test="bookId != null"> AND B.BOOK_ID = #{bookId} </if>-->
后来我完全凌乱了,因而就从头开始写,结果就行了。mybatis
小结:架构
出现的报错可能跟我以前写了太多的if 判断语句有关,因而先写一个简单的并发
<if test="userName != null"> AND A.USER_NAME like '%' || #{userName} || '%' </if>
这个能够执行,其余再有什么条件加进来,稍微修改以后,均可以正常运行。app
在此我向你们推荐一个架构学习交流群。交流学习群号:821169538 里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化、分布式架构等这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多。
<if test="userName != null"> AND A.USER_NAME like concat(concat('%','${userName}'),'%') </if> <if test="userType != null"> AND A.USER_TYPE = #{userType} </if> <if test="mobilePhoneNo != null"> AND A.MOBILE_PHONE_NO like '%' || #{mobilePhoneNo} || '%' </if> <if test="bookInfo.bookId != null"> AND B.BOOK_ID = #{bookInfo.bookId} </if>
出处:https://yq.aliyun.com/articles/623193?spm=a2c4e.11157919.spm-cont-list.327.25b227ae7RC3tZ