ibatis批量处理插入实例

getSqlMapClientTemplate().execute(new SqlMapClientCallback() {

public Object doInSqlMapClient(SqlMapExecutor sqlMapExecutor) throws SQLException {}

}

SqlMapClientTemplate为 org.springframework.orm.ibatis.SqlMapClientTemplate

sqlMapExecutor 为ibatis包中的com.ibatis.sqlmap.client Interface SqlMapExecutor在系统中,提取数据循环计算后,每次需要有大概3000条左右的数据需要提交到数据库。以前在循环中单条插入,开始只有200条左右的数据,看不出性能上的问题,现在数据量增长了很多,所以需要对提交功能做一下优化。spring集成了ibatis的批量提交的功能,我们只要调用API就可以了
首先在你的dao中需要继承org.springframework.orm.ibatis.support.SqlMapClientDaoSupport
然后在代码中调用getSqlMapClientTemplate方法, 覆写SqlMapClientCallback类中的doInSqlMapClient的方法
public void insertTreeCateBatch(final List<TreeCate> TreeCateList) throws DataAccessException{
this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){
public Object doInSqlMapClient(SqlMapExecutor executor)
throws SQLException {
executor.startBatch(); //一定要有,通知开始批量
int batch = 0;
for(TreeCate TreeCate:TreeCateList){
//调用获取sequence的方法。如果没有的话就去掉这行代码。
TreeCate.setTreeCateId(getNextId());
//参数1为:ibatis中需要执行的语句的id ,参数2为要插入的数据
executor.insert("TreeCate_insertTreeCate", TreeCate);
batch++;
//每500条批量提交一次。
if(batch==500){
executor.executeBatch();
batch = 0;
}
}
executor.executeBatch(); //将最后的数据执行,最后不够500条的数据
return null;
}
});
}
批量插入减少了获取数据库连接池的次数,经过测试可以提高60%到70%的性能!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值