foreach 用于迭代传入过来的参数,在sql中通常放在in关键字后面。
它的属性介绍分别是
- collection:表示传入过来的参数的数据类型。该参数为必选。要做 foreach 的对象,作为入参时,List 对象默认用 list 代替作为键,数组对象有 array 代替作为键,Map 对象没有默认的键。当然在作为入参时可以使用 @Param(“keyName”) 来设置键,设置 keyName 后,list,array 将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果 User 有属性 List ids。入参是 User 对象,那么这个 collection = “ids” 如果 User 有属性 Ids ids;其中 Ids 是个对象,Ids 有个属性 List id;入参是 User 对象,那么 collection = “ids.id”
- 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
- 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map。
- item: 循环体中的具体对象。支持属性的点路径访问,如 item.age,item.info.details。具体说明:在 list 和数组中是其中的对象,在 map 中是 value,该参数为必选。(它是每一个元素进行迭代时的别名)
- index:在 list 和数组中,index 是元素的序号;在 map 中,index 是元素的 key。
- open:表示该语句以什么开始
- close:表示该语句以什么结束
- separator:表示在每次进行迭代之间以什么符号作为分隔符
1.配置文件
jdbc.properties,需要注意,需要加allowMultiQueries=true配置
- #MySql
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/mybatis?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true
- jdbc.username=root
- jdbc.password=root
- <?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="jdbc.properties"/>
- <typeAliases>
- <package name="com.mybatis.model"/>
- </typeAliases>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="${jdbc.driverClassName}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </dataSource>
- </environment>
- <environment id="test">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="${jdbc.driverClassName}" />
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <package name="com.mybatis.mappers"/>
- </mappers>
- </configuration>
- import java.util.List;
- import java.util.Map;
- import com.mybatis.model.Student;
- public interface StudentMapper {
- /**
- * 通过List集合批量插入
- * @param list
- * @return
- */
- public int batchInsertStudentWithList(List<Student> list);
- /**
- * 通过IdList进行Update特定字段为特定值
- * @param list
- * @return
- */
- public int batchUpdateByIdList(List<Integer> list);
- /**
- * 通过Map批量更新
- * @param map
- * @return
- */
- public int batchUpdateStudentWithMap(Map<String, Object> map);
- /**
- * 通过List集合批量更新
- * @param list
- * @return
- */
- public int batchUpdateStudentWithList(List<Student> list);
- /**
- * 通过数组进行批量删除
- * @param array
- * @return
- */
- public int batchDeleteStudentWithArray(int array[]);
- /**
- * 能过IdList进行批量删除
- * @param list
- * @return
- */
- public int batchDeleteStudentWithIdList(List<Integer> list);
- /**
- * 通过list删除
- * @param list
- * @return
- */
- public int batchDeleteStudentWithList(List<Student> list);
- /**
- * 通过list中对象进行删除
- * @param list
- * @return
- */
- public int batchDeleteStudentWithListOnlyId(List<Student> list);
- }
- <?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.mybatis.mappers.StudentMapper">
- <!-- 1,size:表示缓存cache中能容纳的最大元素数。默认是1024;
- 2,flushInterval:定义缓存刷新周期,以毫秒计;
- 3,eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in
- first out,先进先出)
- 4,readOnly:默认值是false,假如是true的话,缓存只能读。 -->
- <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false" />
- <resultMap type="Student" id="StudentResult">
- <id property="id" column="id" />
- <result property="name" column="name" />
- </resultMap>
- <delete id="batchDeleteStudentWithArray" parameterType="java.lang.String">
- DELETE FROM t_student where id in
- <foreach item="idItem" collection="array" open="(" separator=","
- close=")">
- #{idItem}
- </foreach>
- </delete>
- <delete id="batchDeleteStudentWithIdList" parameterType="java.util.List">
- DELETE FROM t_student where id in
- <foreach collection="list" item="idItem" index="index" open="("
- separator="," close=")">
- #{idItem}
- </foreach>
- </delete>
- <delete id="batchDeleteStudentWithListOnlyId" parameterType="java.util.List">
- DELETE FROM t_student where id in
- <foreach collection="list" index="index" item="item" open="("
- separator="," close=")">
- #{item.id}
- </foreach>
- </delete>
- <!-- 效率低,不推荐 -->
- <delete id="batchDeleteStudentWithList" parameterType="java.util.List">
- <foreach collection="list" item="item" index="index" open="" close="" separator=";">
- DELETE FROM t_student
- where id=#{item.id}
- </foreach>
- </delete>
- <update id="batchUpdateByIdList" parameterType="java.util.List">
- UPDATE t_student set name='test' where id in
- <foreach collection="list" item="idItem" index="index" open="("
- separator="," close=")">
- #{idItem}
- </foreach>
- </update>
- <update id="batchUpdateStudentWithList" parameterType="java.util.List">
- <foreach collection="list" item="item" index="index" open="" close="" separator=";">
- UPDATE t_student
- <set>
- name=#{item.name}
- </set>
- where id=#{item.id}
- </foreach>
- </update>
- <update id="batchUpdateStudentWithMap" parameterType="java.util.Map">
- UPDATE t_student SET name = #{name} WHERE id IN
- <foreach collection="idList" index="index" item="idItem" open="("
- separator="," close=")">
- #{idItem}
- </foreach>
- </update>
- <insert id="batchInsertStudentWithList" parameterType="java.util.List">
- INSERT INTO /*+append_values */ t_student (name)
- VALUES
- <foreach collection="list" item="item" index="index" separator=",">
- (#{item.name})
- </foreach>
- </insert>
- </mapper>
- package com.mybatis.util;
- import java.io.InputStream;
- import org.apache.ibatis.io.Resources;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
- import org.apache.ibatis.session.SqlSessionFactoryBuilder;
- public class SqlSessionFactoryUtil {
- private static SqlSessionFactory sqlSessionFactory;
- public static SqlSessionFactory getSqlSessionFactory(){
- if(sqlSessionFactory==null){
- InputStream inputStream=null;
- try{
- inputStream=Resources.getResourceAsStream("mybatis-config.xml");
- sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return sqlSessionFactory;
- }
- public static SqlSession openSession(){
- return getSqlSessionFactory().openSession();
- }
- }
- package com.mybatis.model;
- import java.io.Serializable;
- public class Student implements Serializable {
- private Integer id;
- private String name;
- private byte[] pic;// blob
- private String remark;// clob
- public Student() {
- super();
- // TODO Auto-generated constructor stub
- }
- public Student(Integer id, String name) {
- super();
- this.id = id;
- this.name = name;
- }
- public Student(String namee) {
- super();
- this.name = name;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public byte[] getPic() {
- return pic;
- }
- public void setPic(byte[] pic) {
- this.pic = pic;
- }
- public String getRemark() {
- return remark;
- }
- public void setRemark(String remark) {
- this.remark = remark;
- }
- @Override
- public String toString() {
- return "Student [id=" + id + ", name=" + name + ", remark=" + remark + "]";
- }
- }
- package com.mybatis.service;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.log4j.Logger;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import com.mybatis.mappers.StudentMapper;
- import com.mybatis.model.Student;
- import com.mybatis.util.SqlSessionFactoryUtil;
- public class StudentBatchTest {
- private static Logger logger=Logger.getLogger(Student.class);
- private SqlSession sqlSession=null;
- private StudentMapper studentMapper=null;
- /**
- * 测试方法前调用
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- sqlSession=SqlSessionFactoryUtil.openSession();
- studentMapper=sqlSession.getMapper(StudentMapper.class);
- }
- /**
- * 测试方法后调用
- * @throws Exception
- */
- @After
- public void tearDown() throws Exception {
- sqlSession.close();
- }
- //通过list进行批量插入
- @Test
- public void batchInsertStudentWithList(){
- List<Student> list= new ArrayList<Student>();
- for(int i = 2;i < 10;i++){
- Student student = new Student();
- student.setName("test" + i);
- list.add(student);
- }
- int n=studentMapper.batchInsertStudentWithList(list);
- System.out.println("成功插入"+n+"条记录");
- sqlSession.commit();
- }
- //分页批量插入
- @Test
- public void batchInsertStudentPage(){
- List<Student> list= new ArrayList<Student>();
- for(int i = 0;i < 2000;i++){
- Student student = new Student();
- student.setName("test" + i);
- list.add(student);
- }
- try {
- save(list);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void save(List<Student> uidCodeList) throws Exception {
- SqlSession batchSqlSession = null;
- try {
- batchSqlSession =SqlSessionFactoryUtil.openSession();//获取批量方式的sqlsession
- int batchCount = 1000;//每批commit的个数
- int batchLastIndex = batchCount - 1;//每批最后一个的下标
- for(int index = 0; index < uidCodeList.size()-1;){
- if(batchLastIndex > uidCodeList.size()-1){
- batchLastIndex = uidCodeList.size() - 1;
- batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1));
- batchSqlSession.commit();
- System.out.println("index:"+index+" batchLastIndex:"+batchLastIndex);
- break;//数据插入完毕,退出循环
- }else{
- batchSqlSession.insert("com.mybatis.mappers.StudentMapper.batchInsertStudentWithList", uidCodeList.subList(index, batchLastIndex+1)); batchSqlSession.commit();
- System.out.println("index:"+index+" batchLastIndex:"+batchLastIndex);
- index = batchLastIndex + 1;//设置下一批下标
- batchLastIndex = index + (batchCount - 1);
- }
- }
- }finally{
- batchSqlSession.close();
- }
- }
- //通过IdList批量更新
- @Test
- public void batchUpdateByIdList() {
- logger.info("通过IdList批量更新");
- List<Integer> list = new ArrayList<Integer>();
- list.add(5);
- list.add(6);
- int n = studentMapper.batchUpdateByIdList(list);
- System.out.println("成功更新" + n + "条记录");
- sqlSession.commit();
- }
- //通过map进行批量更新
- @Test
- public void batchUpdateStudentWithMap() {
- List<Integer> ls = new ArrayList<Integer>();
- for (int i = 5; i < 7; i++) {
- ls.add(i);
- }
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("idList", ls);
- map.put("name", "小群11");
- int n = studentMapper.batchUpdateStudentWithMap(map);
- System.out.println("成功更新" + n + "条记录");
- sqlSession.commit();
- }
- //通过list批量更新
- @Test
- public void batchUpdateStudentWithList() {
- logger.info("更新学生(带条件)");
- List<Student> list = new ArrayList<Student>();
- list.add(new Student(6, "张三aa"));
- list.add(new Student(6, "李四aa"));
- int n = studentMapper.batchUpdateStudentWithList(list);
- System.out.println("成功更新" + n + "条记录");
- sqlSession.commit();
- }
- //通过Array进行批量删除
- @Test
- public void batchDeleteStudentWithArray() {
- logger.info("删除学生,通过Array");
- int array[] = new int[] { 3, 4 };
- studentMapper.batchDeleteStudentWithArray(array);
- sqlSession.commit();
- }
- @Test
- public void batchDeleteStudentWithIdList() {
- logger.info("通过IdList批量更新");
- List<Integer> list = new ArrayList<Integer>();
- list.add(9);
- list.add(10);
- int n = studentMapper.batchDeleteStudentWithIdList(list);
- System.out.println("成功删除" + n + "条记录");
- sqlSession.commit();
- }
- @Test
- public void batchDeleteStudentWithList() {
- logger.info("通过IdList批量更新");
- List<Student> list = new ArrayList<Student>();
- list.add(new Student(12, null));
- list.add(new Student(13, null));
- int n = studentMapper.batchDeleteStudentWithList(list);
- System.out.println("成功删除" + n + "条记录");
- sqlSession.commit();
- }
- @Test
- public void batchDeleteStudentWithListOnlyId() {
- logger.info("通过IdList批量更新");
- List<Student> list = new ArrayList<Student>();
- list.add(new Student(14, null));
- list.add(new Student(15, null));
- int n = studentMapper.batchDeleteStudentWithListOnlyId(list);
- System.out.println("成功删除" + n + "条记录");
- sqlSession.commit();
- }
- }