问题描述
我正在尝试在MyBatis中定义一个简单的@Select
批注,以基于由IN子句定义的条件来获取对象的集合. SQL看起来像:
I'm trying to define a simple @Select
annotation in MyBatis to get a collection of objects based on criteria defined by an IN clause. The SQL looks something like:
SELECT * FROM employees WHERE employeeID IN (1, 2, 3);
该列表是动态生成的,因此我不知道它将具有多少个参数.我只想传递List
值,例如:
The list is generated dynamically, so I don't know how many parameters it will have. I'd like to just pass in a List
of values, something like:
@Select("SELECT * FROM employees WHERE employeeID IN( #{employeeIds} )")
List<Employee> selectSpecificEmployees(@Param("employeeIds") List<Integer> employeeIds);
我正在创建Mapper
的实例,在其中定义了上面的注释,并按如下方式调用它:
I'm creating an instance of the Mapper
where the annotation above is defined and calling it as follows:
List<Integer> empIds = Arrays.asList(1, 2, 3);
List<Employee> result = mapper.selectSpecificEmployees(empIds);
我发现这行不通.
我认为问题出在注释本身.这似乎是一个相当普遍的要求.我是否需要自己将List
转换为String
并将其作为String
参数而不是List<Integer>
传递?还是有其他语法可以将List
作为参数传递给MyBatis批注?
I think the problem is in the annotation itself. This seems like it would be a fairly common requirement. Do I need to convert the List
to a String
myself and pass that in as a String
parameter instead of a List<Integer>
? Or is there some other syntax for passing a List
as a parameter to a MyBatis annotation?
推荐答案
我以前从未使用过注解和MyBatis.我一直走过xml配置文件路由(不是暗示使用批注有什么问题;只是在解释我不能为您提供帮助).
I've never used annotations and MyBatis before; I've always gone the xml configuration file route (not implying there is anything wrong with using annotations; just explaining I can't help you there).
话虽如此,《 MyBatis用户指南》中的第46页:
That being said, page 46 from the MyBatis user guide:
动态SQL的另一个常见需求是需要迭代一个 收集时,通常会建立一个IN条件.例如:
Another common necessity for dynamic SQL is the need to iterate over a collection, often to build an IN condition. For example:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
这篇关于我可以将列表作为参数传递给MyBatis映射器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!