一, 结论
这里先给大家看一下结论
Oracle 中, 拼接模糊查询的正确写法
- SELECT A.USER_ID,
- A.USER_NAME
- FROM USER A
- AND A.USER_NAME like concat(concat('%','w'),'%')
或者
AND A.USER_NAME like '%' || 'w' || '%'
Mybatis 中, 拼接模糊查询的正确写法
<select id="selectByName" resultMap="BaseResultMap">
SELECT A.USER_ID,
A.USER_NAME
FROM T_BASE_USER_INFO 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>
注意 Mybatis 中, 拼接模糊查询的用法
#, 是将传入的值当做字符串的形式. 所以拼接的时候 #{userName} 默认自带引号.
例如: ${userName} 直接转为'zhen'.
$, 是将传入的数据直接显示生成 sql 语句. 所以拼接的时候 ${userName} 没有默认引号.
例如:${userName} 直接转为 zhen .
二, 技巧:
刚开始写的时候一直报错, 报错信息是这样的:
"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="_parameter != 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="roleId != null">
- AND B.ROLE_ID = #{roleId}
- </if>-->
后来我彻底凌乱了, 于是就从头开始写, 结果就好了.
小结:
出现的报错可能跟我之前写了太多的 if 判断语句有关, 于是先写一个简单的
<if test="userName != null">
AND A.USER_NAME like '%' || #{userName} || '%'
</if>
这个可以执行, 其他再有什么条件加进来, 稍微修改之后, 都可以正常运行.
- <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="baseRoleInfo.roleId != null">
- AND B.ROLE_ID = #{baseRoleInfo.roleId}
- </if>
来源: https://yq.aliyun.com/articles/623193