在SpringBoot/Mybatis中,Mapper如果要处理 IN 语句,需要利用脚本功能。
如果按普通字符串处理,无法避免SQL注入攻击,所以建议按下面的方式处理:
考虑以下查询(Mybatis):
SELECT field1, avg(field2), min(field3), max(field4)
FROM your_table
WHERE create_time >= #{start} AND create_time < #{end}
AND hour(create_time) IN (#{hours})
GROUP BY field1
如果直接运行,会SQL语法报错,因为 #{hours} 无法在mapper中正确处理。
正确的Mapper中的代码写法:
@Select({"<script>",
" SELECT field1,",
" avg(field2)",
" min(field3)",
" max(field4)",
" FROM your_table",
" WHERE create_time <![CDATA[ >= ]]> #{start} AND create_time <![CDATA[ < ]]> #{end} ",
" <foreach item='item' index='index' collection='hours' open=\"AND hour(create_time) IN (\" separator=',' close=\")\">",
" #{item}",
" </foreach>",
" GROUP BY field1",
"</script>",})
List<Result> getReport(LocalDateTime start, LocalDateTime end, List<Integer> hours);