Mybatis 传递数组给sql解析 解决not in失效问题

接上文:Vue get请求传递数组,springboot接受数组

一开始解析数组的思路是下面这样的,不会报错,但not in失效,没有排除任何id

@Select("SELECT * FROM some_table WHERE id NOT IN (#{item})")
List<SomeEntity> selectByIds(@Param("item") List<Integer> ids);

原因是sql语句可能会被解析为:

SELECT * FROM some_table WHERE id IN ('[1,2]')

我们改用script里的foreach标签解析

@Select({
	"<script>",
	"SELECT * FROM your_table",
	"WHERE id",
	"<if test='ids!=null and ids.size()>0'>",
	"NOT IN",
			"<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')'>",
		    "#{item}",
		    "</foreach>",
	"</if>",
	"</script>"
})
List<SomeEntity> selectByIds(@Param("item") List<Integer> ids);

注意:
1.由于在@Select()加了花括号{},字符串之间用逗号分隔即可。
2.if标签可以使sql处理空值时忽略条件,这样就不会报错。
2.如果提示mybatis foreach标签的 Parameter ‘item’ not found.是因为没有添加script标签

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-15 02:56:03       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-15 02:56:03       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-15 02:56:03       62 阅读
  4. Python语言-面向对象

    2024-07-15 02:56:03       72 阅读

热门阅读

  1. sqlalchemy使用with_entities返回指定数据列

    2024-07-15 02:56:03       17 阅读
  2. Redis如何高效安全的遍历所有key

    2024-07-15 02:56:03       13 阅读
  3. ansible安装

    2024-07-15 02:56:03       18 阅读
  4. RocketMQ~生产者与消费者的消费模式(pull or push)

    2024-07-15 02:56:03       20 阅读
  5. Go语言基础数据类型、变量及自增语法

    2024-07-15 02:56:03       22 阅读
  6. Linux使用python调用串口<Ubuntu>

    2024-07-15 02:56:03       20 阅读
  7. 求职笔记day3

    2024-07-15 02:56:03       22 阅读
  8. WSL2 的安装与运行 Linux 系统

    2024-07-15 02:56:03       19 阅读
  9. Android C++系列:Linux网络(五)常见术语

    2024-07-15 02:56:03       21 阅读
  10. DP讨论——适配器、桥接模式等通用理解

    2024-07-15 02:56:03       18 阅读