最近项目中需要进行分表就使用了ShardingJDBC做数据库中间层操作
之前sql中有写批量插入,而ShardingJDBC不支持insert xxx values(...),(...),(...)语句
故需要手动开启事务,循环插入并提交事务(与之前批量插入语句性能未做比较)
@Component
public class UserManager implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Autowired
private UserDao UserDao;
public void createUseres(List<User> UserList) {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
definition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
DataSourceTransactionManager transactionManager = (DataSourceTransactionManager)
applicationContext.getBean("transactionManager");
TransactionStatus transactionStatus = transactionManager.getTransaction(definition);
for (User User : UserList) {
//UserDao有create方法,单条插入
applicationContext.getBean(UserDao.class).create(User);
}
transactionManager.commit(transactionStatus);
}
@Override
public void setApplicationContext(ApplicationContext ac) throws BeansException {
applicationContext = ac;
}
}
原文地址:https://www.cnblogs.com/chenvi/p/8340039.html
时间: 2024-11-27 10:44:24