亲宝软件园·资讯

展开

MyBatis批量添加数据 MyBatis批量添加数据2种实现方法

shouyaya 人气:0

1.通过for each标签拼接sql(数量较少的时候使用)

  a.拼接values()

  public int addPersons(@Param("persons") List<Person> persons);//接口

<insert id="addPersons">
 insert into person(username,email,gender) VALUES
  <foreach collection="persons" item="person" separator=";">
   (#{person.username},#{person.email},#{person.gender})
  </foreach>
 </insert>

<!--类似的效果 insert into person(username,email,gender) VALUES("zhangsan","zhangsan@163.com","F"),("lisi","lisi@163.com","F"),... -->

  b.拼接insert sql语句(需设置属性allowMultiQueries=true)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true //需设置属性
jdbc.username=root
jdbc.password=123

public int addPersons(@Param("persons") List<Person> persons);//接口

<insert id="addPersons">
  insert into person(username,email,gender) VALUES
  <foreach collection="persons" item="person" separator=",">
   (#{person.username},#{person.email},#{person.gender})
  </foreach>
 </insert>
<!--类似的效果 insert into person(username,email,gender) VALUES("tom","zhangsan@163.com","F");
        insert into person(username,email,gender) VALUES("jerry","lisi@163.com","F");...-->

2.基于Session的ExecutorType进行批量添加

先定义一条插入一条记录的方法

public int addPerson(User user); //接口

 <insert id="addPerson" parameterType="user">
  insert into t_user(username,address) VALUES (#{username},#{address})
 </insert>

在java代码中使用

public void testBatchForExecutor()
  {
    SqlSession sqlSession = this.getSqlSessionFactory().openSession(ExecutorType.BATCH); //通过session设置ExecutorType开启批量添加,类似jdbc的addBatch操作
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    for (int i = 0; i <10000 ; i++)
    {
      personMapper.addPerson(new User("jerry","bj"));
    }
    sqlSession.commit();
    sqlSession.close();
  }

加载全部内容

相关教程
猜你喜欢
用户评论