刚开始接触springmvc+ibatis架构时遇到批量插入更新数据库的问题。
- public class BaseDao extends SqlMapClientDaoSupport {
- @Resource(name = "sqlMapClient")
- private SqlMapClient sqlMapClient;
- @PostConstruct
- public void initSqlMapClient() {
- super.setSqlMapClient(sqlMapClient);
- }
- }
BaseDao一般的写法如上,在继承basedao后,我们使用this.getSqlMapClientTemplate()方法调用现成的数据库操作方法(增删改查),但是这里面却没有批量操作方法
我们需要利用execute和SqlMapClientCallback
- protected void batchInsert(final List<T> objList, final String statment, final int i) throws DataAccessException {
- this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
- public T doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
- executor.startBatch();
- int batch = 0;
- for (T obj : objList) {
- executor.insert(statment, obj);
- batch++;
- if (batch == i) {
- executor.executeBatch();
- batch = 0;
- }
- }
- executor.executeBatch();
- return null;
- }
- });
- }
- /**
- * 批量更新
- *
- * @param objList
- * 更新对象类表
- * @param statment
- * sqlID名称
- * @param i
- * 更新数量
- * @throws DataAccessException
- */
- @SuppressWarnings("unchecked")
- protected void batchUpdate(final List<T> objList, final String statment, final int i) throws DataAccessException {
- this.getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
- public T doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
- executor.startBatch();
- int batch = 0;
- for (T obj : objList) {
- executor.update(statment, obj);
- batch++;
- if (batch == i) {
- executor.executeBatch();
- batch = 0;
- }
- }
- executor.executeBatch();
- return null;
- }
- });
- }
- public class BaseDao<T extends Entity> extends SqlMapClientDaoSupport
这样就能在自己的dao层中直接调用批量方法...