在xml的sql语句中,不能直接用大于号、小于号、单引号、双引号,要用转义字符替代
在sql语句里动态赋值时,如果说需要用单引号,不能直接用 ‘ 表示:
举例:
<select id="selectBusCarTrackByCarId" parameterType="net.hehang.base.entity.Search" resultMap="result_BusCarTrack_Map">
select
t.*,to_char(t.UP_DATE,'yyyy-mm-dd hh24:mi:ss') upDate123
from BUS_CAR_TRACK t
<where>
1=1
<if test="carId != null and carId !=''">
AND t.CAR_ID = #{carId}
</if>
<if test="curDate != null and curDate !=''">
AND to_char(t.UP_DATE,'yyyy-mm-dd')='#{curDate}'
</if>
</where>
order by t.UP_DATE desc
</select>
项目运行进行测试时,报错:
严重: Servlet.service() for servlet [SpringMVC] in context with path [/smarter_SecurityManagement] threw exception [Request processing failed; nested exception is org.springframework.jdbc.InvalidResultSetAccessException:
### Error querying database. Cause: java.sql.SQLException: 无效的列索引
### The error may exist in file [D:\WebServer\apache-tomcat-7.0.69-windows-x64\apache-tomcat-7.0.69\webapps\smarter_SecurityManagement\WEB-INF\classes\net\hehang\indexManage\dao\mapping\BusCarTrackMapper.xml]
### The error may involve net.hehang.indexManage.dao.BusCarTrackDao.selectBusCarTrackByCarId-Inline
### The error occurred while setting parameters
### SQL: SELECT count(*) FROM (SELECT t.*, to_char(t.UP_DATE, 'yyyy-mm-dd hh24:mi:ss') upDate123 FROM BUS_CAR_TRACK t WHERE 1 = 1 AND t.CAR_ID = ? AND to_char(t.UP_DATE, 'yyyy-mm-dd') = '?') table_count
### Cause: java.sql.SQLException: 无效的列索引
debug模式下,发现所需的carId和curDate都是有值的,且格式正确;
错误原因是mapper配置里:
AND to_char(t.UP_DATE,'yyyy-mm-dd')='#{curDate}'
xml配置里不能直接用特殊符号,需要进行转义;
修改为:
AND to_char(t.UP_DATE,'yyyy-mm-dd')=#{curDate}
因为我的curDate本来就是String类型,此处不需要再加单引号限定了,如果某些地方确实需要单引号,要用'替换。
其他的例如
<= 应表示为:<= 或是<&= , >=以此类推
其他转义字符
< |
< |
小于号 |
> |
> |
大于号 |
& |
& |
和 |
' |
’ |
单引号 |
" |
" |
双引号 |