批量添加怎么做呢图仓?
1:mybatis <foreach> 標(biāo)簽拼接 insert values海蔽;
2:今天說第二種:mybatis ExecutorType.BATCH拥刻;
大致邏輯就是從 sqlsessionfactory 取出 mapper淮腾,然后 sqlsession 是 ExecutorType.BATCH;
再獲取的 mapper 再執(zhí)行 insert 等操作谭梗;
原理類似: 開啟 一個(gè) mysql 事物监婶,寫一批的insert旅赢,最后事物提交,錯(cuò)誤就回滾惑惶;
具體代碼如下:
@Component?
public class SqlSessionBatch<T> {
? ? public class Entry{
? ? ? ? private T t;
? ? ? ? private SqlSession sqlSession;
? ? ? ? public Entry(T t, SqlSession sqlSession) {
? ? ? ? ? ? this.t= t;
? ? ? ? ? ? this.sqlSession= sqlSession;
}
? ? ? ? public T getT() {
? ? ? ? ? ? return t;
}
? ? ? ? public void setT(T t) {
? ? ? ? ? ? this.t= t;
}
? ? ? ? public SqlSession getSqlSession() {
? ? ? ? ? ? return sqlSession;
}
? ? ? ? public void setSqlSession(SqlSession sqlSession) {
? ? ? ? ? ? this.sqlSession= sqlSession;
}
}
? ? @Autowired
? ? private BeanFactory beanFactory;
? ? /**
? ? * 獲取指定 mapper 使用的 SqlSessionFactory(適合多數(shù)據(jù)源配置多個(gè) SqlSessionFactory)
? ? * @param mapper
? ? * @return
? ? */
? ? public Entry getSqlSession(Class<T> mapper) {
? ? ? ? Asserts.beanNotEmpty(mapper, "params mapper can't null!");
? ? ? ? // 獲取每個(gè)數(shù)據(jù)源配置的sqlSessionTemplate
? ? ? ? String[] sqlSessionTemplates=
? ? ? ? ? ? ? ? ((DefaultListableBeanFactory)beanFactory).getBeanNamesForType(SqlSessionFactory.class);
? ? ? ? for(String sqlSessionTemplate: sqlSessionTemplates){
? ? ? ? ? ? SqlSessionFactory sf= beanFactory.getBean(sqlSessionTemplate, SqlSessionFactory.class);
? ? ? ? ? ? if(sf.getConfiguration().hasMapper(mapper)){
? ? ? ? ? ? ? ? SqlSession sqlSession= sf.openSession(ExecutorType.BATCH, false);
? ? ? ? ? ? ? ? return new Entry(sqlSession.getMapper(mapper), sqlSession);
}
}
? ? ? ? throw new GeneralException(String.format("batch error: mapper - %s can't found!", mapper.getName()));
}
? ? /**
? ? * 提交
? ? * @param e
? ? */
? ? public void commit(Entry e){
? ? ? ? e.getSqlSession().flushStatements();
? ? ? ? e.getSqlSession().clearCache();
}
}
然后在service實(shí)現(xiàn)層這么用:
@Service
public class UserSiteServiceImpl implements UserSiteService {
? ? @Autowired
? ? private WnUserSiteMapper wnUserSiteMapper;
? ? @Autowired
? ? private SqlSessionBatch<WnUserSiteMapper> userSiteMapperSqlSessionBatch;
??? @Transactional(rollbackFor = Exception.class)
??? protected void batchAddUserSites(List<WnUserSite> userSites) {
? ? SqlSessionBatch.Entry e= userSiteMapperSqlSessionBatch.getSqlSession(WnUserSiteMapper.class);
? ? WnUserSiteMapper userSiteMapper= (WnUserSiteMapper) e.getT();
? ? for(WnUserSite userSite: userSites){
? ? ? ? userSiteMapper.insert(userSite);
???? }
? ????? userSiteMapperSqlSessionBatch.commit(e);
???? }
}
以上就是代碼煮盼;注意一點(diǎn)哦:記得在數(shù)據(jù)源上的bean配置上加上 @EnableTransactionManagement 事物注解哦,
這樣遇到錯(cuò)誤的時(shí)候带污,批量添加的時(shí)候也可以回滾哦僵控;同時(shí)在一個(gè)數(shù)據(jù)源上,mapper不要跨sqlsessionfactory哦