本来想在@select注解中使用动态拼接sql,我的代码中的select注解如下:
@Select({"<script>"
+ "select count(if(ta.dt_created>=#{currentDate},true,null)) currentVolume,"
+ "count(if(ta.dt_created<#{currentDate},true,null)) beforeVolume,Count(*) as volume"
+ "where 1=1"
+ "<if test='finalDecision != null'>"
+ "and ta.final_decision=#{ finalDecision}"
+ "</if>"
+ "</script>"})
启动项目,报错如下:
ERROR org.mybatis.spring.mapper.MapperFactoryBean checkDaoConfig-82 – Error while adding the mapper ‘interface com…mapper.***Mappper’…
Caused by:org.xml.sax.SAXParseException:the content of elements must consist of well-formed character data or markup.
大概意思就是元素的内容必须由格式良好的字符数据或标记组成。刚开始以为不能动态拼接呢。。差点放弃改用xml了,最后仔细看想起来是mybatis的sql规范问题。我的sql中又大于小于符号,对于mybatis的sql中不能直接使用>、<这种符号。
改法1:<![CDATA[ > ]]>、<![CDATA[ < ]]>
改法2: < <= > >= & ’ " 依次替换成 < <= > >= & ' "
下边是我改的成品:
@Select({"<script>"
+ "select count(if(ta.dt_created >= #{currentDate},true,null)) currentVolume,"
+ "count(if(ta.dt_created < #{currentDate},true,null)) beforeVolume,Count(*) as volume"
+ "where 1=1"
+ "<if test='finalDecision != null'>"
+ "and ta.final_decision=#{ finalDecision}"
+ "</if>"
+ "</script>"})