首页 > 其他 > 详细

MyBatis批量新增数据

时间:2020-04-28 23:42:40      阅读:66      评论:0      收藏: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();


    }

 

MyBatis批量新增数据

原文:https://www.cnblogs.com/shouyaya/p/12797984.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!