您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
03-mybatis映射文件深入-动态sql-foreach
发布时间:2025-01-30 19:26:05编辑:雪饮阅读()
-
上篇中主要是实现了用if标签进行动态sql拼接。那么接下来还可以使用foreach标签进行动态sql拼接,尤其是如mysql中in查询,主要是在UserMapper.xml中定义如:
<!--查询操作-in查询-->
<select id="findByIds" parameterType="list" resultType="user">
select * from user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
这里collection接收值如果是list集合就是list,如果是数组就是array,由于这里parameterType接收类型是list,所以这里collection的值也是list。
open与close属性对应开合,例如sql中经常用的in查询是要用括号将需要进行查询的条件一般如多个id,那么这里foreach就可以遍历这些id,所以需要open和close正好对应括号的开括号与关括号,item就是定义循环体里面可以调用的一个标识符,用”#{标识符}”形式在循环体内部调用。separator用于定义多个值的分隔符,像是in查询里面如id多个时候会有逗号分隔。
然后在上篇中的UserMapper.java中对应新增抽象接口方法如:
public List<User> findByIds(List<Integer> ids);
然后编写第二个针对多个id的in查询的实际测试方法如:
@Test
public void test2() throws IOException {
InputStream resourceAsStream= Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
List<Integer> ids=new ArrayList<Integer>();
ids.add(14);
ids.add(15);
List<User> userList=mapper.findByIds(ids);
System.out.println(userList);
sqlSession.close();
}
关键字词:mybatis,sql,foreach