Mybatis的三种批量操作数据的⽅法⽅法1:
使⽤for循环在java代码中insert (不推荐)
⽅法2:
使⽤在l当中使⽤ foreach循环的⽅式进⾏insert
PersonDao.java⽂件
public interface PersonDao {
//这个是使⽤ foreach⽅式的mybatis 批量操作
public void batchInsert(@Param("list")List<Person>list);
}
<insert id="batchInsert" >
insert into person (
id,
person_name,
birthday,
address,
age,
gender
)
values
<foreach collection="list" item="list" index="index" separator="," >
(
#{list.id},
#{list.person_name},
#{list.birthday},
#{list.address},
#{list.age},
#{der}
)
</foreach>
</insert>
主测试函数:
public static void main5(String[] args) throws Exception {
SqlSession session = getSqlSession();
PersonDao pd = Mapper( PersonDao.class );
List<Person>pl = new ArrayList<Person>();
Person p1 = new Person(); p1.setPerson_name("哈哈哈吧");  p1.setAddress("深圳"); p1.setBirthday(new Date());
Person p2 = new Person(); p2.setPerson_name("您好");  p2.setAddress("上海"); p2.setBirthday(new Date());
Person p3 = new Person(); p3.setPerson_name("我是张伟");  p3.setAddress("⼴州"); p3.setBirthday(new Date());
pl.add(p1);
pl.add(p2);
pl.add(p3);
pd.batchInsert(pl);
System.out.println("完成batchInsert");
sessionmit();
session.close();
//pd.batchInsert( pl );
}
⽅法3:
Mybatis内置的 ExecutorType有三种,默认是Simple,该模式下它为每个语句的执⾏创建⼀个新的预处理语句,单条提交sql,⽽batch模式重复使⽤已经预处理的语句,并且批量执⾏所有更新语句,显然 batch的性能更优,
中间在提交的过程中还可以设置等待时间,避免数据库压⼒过⼤。(获取batch模式下的session)
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream( "F:\\myeclipse_workspace\\mybatisGeneratortest\\src\\test\\resources\\l");
SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = ssfb.build(in);
SqlSession session = factory.openSession( ExecutorType.BATCH,false );
批量更新sql语句PersonDao pd = Mapper( PersonDao.class );
int size = 100000;
try {
for(int i=0;i<size;i++){
Person p = new Person();
p.setPerson_name("⼩明"); p.setBirthday(new Date());
pd.insertPeron(p);
if( i % 100 == 0 || i == size - 1 ){ //加上这样⼀段代码有好处,⽐如有100000条记录,每超过 100 条提交⼀次,中间等待10ms,可以避免⼀次性提交过多数据库压⼒过⼤                        sessionmit();
session.clearCache();
Thread.sleep(10);
}
}
} catch (Exception e) {
// TODO: handle exception
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。