两种写法:
一、第一种,在Dao接口中自定义SQL查询,拼接xml字符串
@Select("<script>"
+"select * from mail_contactor where id in(select contacts_id from mail_contactor_group where group_id in"
+ "<foreach item='id' index='index' collection='ids' open='(' separator=',' close=')'>"
+ "#{id}"
+ "</foreach>"
+")"
+ "</script>")
List<MailContactorEntity> getListInGroup(@Param("ids") List<String> ids);
二、第二种,在Dao接口自定义SQL查询,拼接xml对象
@Select({"<script>",
"select id as id,name as name,longitude as lon,latitude as lat,1 as style from risk_camera ",
"where platform_id in ",
"<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
"#{id} ",
"</foreach>",
"and !ISNULL(longitude) and !ISNULL(latitude)",
"</script>"
})
List<VisuaResourceVo> getVisuaList(@Param("ids") List<Long> ids);
个人觉得第一种拼接方式更美观
需要注意的是:
<foreach>标签的collection参数的设置问题,如果参数像上面的例子这样用@Param注解表明了,则用@Param标明的值,否则:
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以,collection的属性值为Map的key
本以为mabatis升级到mybatis-plus能逃过xml的坑了,没想到还有这么多缺陷,要不是项目需要,JPA它不香吗