问题:

偷懒用注解方式写sql的时候,遇到了这个错误。如下图:

	@Select({"<script> ",
				"select * from coupon where over<=#{price} and startTime<=now() and now()<=endTime and id in ",
				"<foreach item='item' index='index' collection='couponIds' open='(' separator=',' close=')'>",
					"#{item}",
				"</foreach>",
				" order by discount desc",
			"</script>"})

在这里插入图片描述

原因分析:

经过查找,使用<script>标签时,内部语句会以xml的形式解析,而 < 或者 > 会被系统认为是标签,而不是大于小于号,所以才会出现问题。

解决方案:

使用<![CDATA[ SQL语句 ]]> 将含有<、>、<=、>=的sql语句包含进去。
如下:

@Select({"<script> ",
			"select * from coupon where <![CDATA[over<=#{price} and startTime<=now() and now()<=endTime]]> and id in ",
				"<foreach item='item' index='index' collection='couponIds' open='(' separator=',' close=')'>",
					"#{item}",
				"</foreach>",
			" order by discount desc",
		"</script>"})

第二种方法:使用转移字符。

符号转义字符
<&lt;
<=&lt;=
>&gt;
>=&gt;=

如下:

@Select({"<script> ",
			"select * from coupon where over &lt;= #{price} and startTime &lt;= now() and now() &lt;= endTime and id in ",
				"<foreach item='item' index='index' collection='couponIds' open='(' separator=',' close=')'>",
					"#{item}",
				"</foreach>",
			" order by discount desc",
		"</script>"})
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐