歡迎您光臨本站 註冊首頁

MyBatis批次新增資料2種實現方法

←手機掃碼閱讀     f2h0b53ohn @ 2020-06-12 , reply:0

1.透過for each標籤拼接sql(數量較少的時候使用)

  a.拼接values()

  public int addPersons(@Param("persons") Listpersons);//介面
 

  insert into person(username,email,gender) VALUES(#{person.username},#{person.email},#{person.gender})

 

  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") Listpersons);//介面
 

  insert into person(username,email,gender) VALUES(#{person.username},#{person.email},#{person.gender})

 

2.基於Session的ExecutorType進行批次新增

先定義一條插入一條記錄的方法

public int addPerson(User user); //介面
 

   insert into t_user(username,address) VALUES (#{username},#{address})

 

在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();    }

       


[f2h0b53ohn ] MyBatis批次新增資料2種實現方法已經有224次圍觀

http://coctec.com/docs/java/show-post-238308.html