问题描述
应用在使用 sharding sphere 来实现加密后,对于 like sql 语句解析抛异常,异常信息如下:
sharding sphere 版本 5.3.2
xml 文件SQL 语句:
<select id="countSchoolByStatus" parameterType="java.lang.Integer" resultType="int">selectcount(id)from school<where><if test="status != null">and `status` = #{status, jdbcType=INTEGER}</if><if test="name != null">and `name` like '%' #{status, jdbcType=INTEGER} '%'</if></where></select>
Caused by: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: Error preparing statement. Cause: org.apache.shardingsphere.sql.parser.exception.SQLParsingException: You have an error in your SQL syntax: selectcount(id)from schoolWHERE `status` = ?and `name` like '%' ? '%', no viable alternative at input '?' at line 7, position 36, near [@15,136:136='?',<42>,7:36]at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77) ~[mybatis-spring-1.3.2.jar:1.3.2]at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446) ~[mybatis-spring-1.3.2.jar:1.3.2]at com.sun.proxy.$Proxy59.selectOne(Unknown Source) ~[na:na]at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:166) ~[mybatis-spring-1.3.2.jar:1.3.2]
解决方案
修改 like % % 的写法,改为 like concat()
<select id="countSchoolByStatus" parameterType="java.lang.Integer" resultType="int">selectcount(id)from school<where><if test="status != null">and `status` = #{status, jdbcType=INTEGER}</if><if test="name != null">and `name` like concat('%', #{status, jdbcType=INTEGER}, '%')</if></where></select>