MyBatis 的 <foreach> 标签用来迭代集合或数组。为了正确使用 <foreach> 标签,我们先看看标签的 DTD 定义,如下:
<!ELEMENT foreach (#PCDATA | include | trim | where | set | foreach | choose | if | bind)*> <!ATTLIST foreach collection CDATA #REQUIRED item CDATA #IMPLIED index CDATA #IMPLIED open CDATA #IMPLIED close CDATA #IMPLIED separator CDATA #IMPLIED >
<foreach> 标签中允许出现 <include>、<trim>、<where>、<set>、<foreach>、<choose>、<if>、<bind> 等标签。支持六个属性,分别如下:
collection:指定待迭代的集合名称,通常是 @Param("collectionName") 中指定的 collectionName;也可以是 bean.collectionName。
item:迭代集合过程中,当前迭代的值
index:迭代索引,从 0 开始
open:将指定的值添加到 <foreach> 标签拼接内容的前面,如:in (1,2,3,4,5) 中的 “(” 符号
close:将指定的值追加到 <foreach> 标签拼接内容的后面,如:in (1,2,3,4,5) 中的 “)” 符号
separator:指定两个元素之前使用什么字符进行分割,如:in (1,2,3,4,5) 中的 “,”
下面通过示例介绍怎样使用 <foreach> 标签构建 IN 条件(样例:select * from users where user_id in (1,2,3,4,5)),比如:
<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>
<foreach> 标签是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个标签是很智能的,它不会偶然地附加多余的分隔符。
注意:你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。当你这么做的时候, MyBatis 会自动将它包装在一个 Map 中,用名称作为键。 List 实例将会以 “list” 作为键,而数组实例将会以 “array” 作为键。
(1)MyBatis 配置文件 mybatis-cfg.xml 内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hxstrive/mybatis/dynamic_sql/demo6/UserMapper.xml" /> </mappers> </configuration>
(2)实体 UserBean.java 代码如下:
package com.hxstrive.mybatis.dynamic_sql.demo6; public class UserBean { private Integer userId; private String name; private String sex; private Integer age; // 忽略 getter 和 setter 方法 @Override public String toString() { return "UserBean{" + "userId=" + userId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } }
(3)Mapper 定义如下
a、UserMapper.java
package com.hxstrive.mybatis.dynamic_sql.demo6; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { List<UserBean> getUserList(@Param("ids") List<Integer> userIdList); }
b、UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.dynamic_sql.demo6.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.dynamic_sql.demo6.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <select id="getUserList" resultMap="RESULT_MAP"> select `user_id`, `name`, `age`, `sex` from `user` <where> `user_id` in <foreach collection="ids" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach> </where> </select> </mapper>
(4)客户端代码如下:
package com.hxstrive.mybatis.dynamic_sql.demo6; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; import java.util.Arrays; import java.util.List; public class DynamicSqlDemo { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/dynamic_sql/demo6/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); System.out.println("\n\n示例1:"); getUserList(sqlFactory); } private static void getUserList(SqlSessionFactory sqlFactory) { SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<UserBean> userBeanList = userMapper.getUserList( Arrays.asList(new Integer[]{1, 3})); for(UserBean userBean : userBeanList) { System.out.println(userBean); } } }
运行客户端代码,将输出如下结果:
2020-09-11 12:49:58,800 DEBUG [org.apache.ibatis.logging.LogFactory] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. 2020-09-11 12:49:58,840 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-11 12:49:58,841 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-11 12:49:58,841 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-11 12:49:58,841 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 示例1: 2020-09-11 12:49:59,105 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Opening JDBC Connection 2020-09-11 12:49:59,619 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - Created connection 710239027. 2020-09-11 12:49:59,623 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo6.UserMapper.getUserList] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@2a556333] 2020-09-11 12:49:59,624 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo6.UserMapper.getUserList] - ==> Preparing: select `user_id`, `name`, `age`, `sex` from `user` WHERE `user_id` in ( ? , ? ) 2020-09-11 12:49:59,677 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo6.UserMapper.getUserList] - ==> Parameters: 1(Integer), 3(Integer) 2020-09-11 12:49:59,785 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo6.UserMapper.getUserList] - <== Total: 2 UserBean{userId=1, name='赫仑', sex='男', age=27} UserBean{userId=3, name='叶星云', sex='女', age=31}
上面示例中,将执行如下 SQL:
select `user_id`, `name`, `age`, `sex` from `user` WHERE `user_id` in ( ? , ? )
该 SQL 语句将返回两条数据。