一、springboot整合事物管理

springboot默认集成事物,只主要在方法上加上@Transactional即可

二、SpringBoot分布式事物管理

使用springboot+jta+atomikos 分布式事物管理

1、pom文件

 <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--mybatis起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid 依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--atomikos依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
</dependencies>

 2、application.properties信息

# Mysql 1
mysql.datasource.test.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
mysql.datasource.test.username = root
mysql.datasource.test.password = root mysql.datasource.test.minPoolSize = 3
mysql.datasource.test.maxPoolSize = 25
mysql.datasource.test.maxLifetime = 20000
mysql.datasource.test.borrowConnectionTimeout = 30
mysql.datasource.test.loginTimeout = 30
mysql.datasource.test.maintenanceInterval = 60
mysql.datasource.test.maxIdleTime = 60
mysql.datasource.test.testQuery = select 1 # Mysql 2
mysql.datasource.test2.url =jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
mysql.datasource.test2.username =root
mysql.datasource.test2.password =root mysql.datasource.test2.minPoolSize = 3
mysql.datasource.test2.maxPoolSize = 25
mysql.datasource.test2.maxLifetime = 20000
mysql.datasource.test2.borrowConnectionTimeout = 30
mysql.datasource.test2.loginTimeout = 30
mysql.datasource.test2.maintenanceInterval = 60
mysql.datasource.test2.maxIdleTime = 60
mysql.datasource.test2.testQuery = select 1

 3、创建多数据源

@Configuration
// basePackages 最好分开配置 如果放在同一个文件夹可能会报错
@MapperScan(basePackages = "com.itmayiedu.test1", sqlSessionTemplateRef = "testSqlSessionTemplate")
public class TestMyBatisConfig1 { // 配置数据源
@Primary
@Bean(name = "testDataSource")
public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {
MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
mysqlXaDataSource.setUrl(testConfig.getUrl());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
mysqlXaDataSource.setPassword(testConfig.getPassword());
mysqlXaDataSource.setUser(testConfig.getUsername());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
xaDataSource.setXaDataSource(mysqlXaDataSource);
xaDataSource.setUniqueResourceName("testDataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());
xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());
xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());
xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());
xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());
xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());
xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());
xaDataSource.setTestQuery(testConfig.getTestQuery());
return xaDataSource;
} @Primary
@Bean(name = "testSqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Primary
@Bean(name = "testSqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
// basePackages 最好分开配置 如果放在同一个文件夹可能会报错
@Configuration
@MapperScan(basePackages = "com.itmayiedu.test2", sqlSessionTemplateRef = "test2SqlSessionTemplate")
public class TestMyBatisConfig2 { // 配置数据源
@Bean(name = "test2DataSource")
public DataSource testDataSource(DBConfig1 testConfig) throws SQLException {
MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
mysqlXaDataSource.setUrl(testConfig.getUrl());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
mysqlXaDataSource.setPassword(testConfig.getPassword());
mysqlXaDataSource.setUser(testConfig.getUsername());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true); AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
xaDataSource.setXaDataSource(mysqlXaDataSource);
xaDataSource.setUniqueResourceName("test2DataSource"); xaDataSource.setMinPoolSize(testConfig.getMinPoolSize());
xaDataSource.setMaxPoolSize(testConfig.getMaxPoolSize());
xaDataSource.setMaxLifetime(testConfig.getMaxLifetime());
xaDataSource.setBorrowConnectionTimeout(testConfig.getBorrowConnectionTimeout());
xaDataSource.setLoginTimeout(testConfig.getLoginTimeout());
xaDataSource.setMaintenanceInterval(testConfig.getMaintenanceInterval());
xaDataSource.setMaxIdleTime(testConfig.getMaxIdleTime());
xaDataSource.setTestQuery(testConfig.getTestQuery());
return xaDataSource;
} @Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

4、启动加载配置

@EnableConfigurationProperties(value = { DBConfig1.class, DBConfig2.class })

5、controller类

@RestController
public class MybatisMultilDataSourceController {
@Autowired
private UserServiceTest01 userServiceTest01;
@Autowired
private UserServiceTest02 userServiceTest02; @RequestMapping("/insertUserTest1")
public Integer insertUserTest1(String name, Integer age) {
return userServiceTest01.insertUser(name, age);
} @RequestMapping("/insertUserTest2")
public Integer insertUserTest2(String name, Integer age) {
return userServiceTest02.insertUser(name, age);
} @RequestMapping("/insertUserTest01AndTest02")
public int insertUserTest01AndTest02(String name, Integer age) {
return userServiceTest02.insertUserTest01AndTest02(name, age);
}

6、多个Mapper接口

根据包区分

public interface UserMapperTest01 {

    // 添加
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
public interface UserMapperTest02 {

    // 添加
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}

7、多个service

根据包区分

@Service
@Slf4j
public class UserServiceTest02 {
@Autowired
private UserMapperTest02 userMapperTest02;
@Autowired
private UserMapperTest01 userMapperTest01; @Transactional(transactionManager = "test2TransactionManager")
public int insertUser(String name, Integer age) {
int insertUserResult = userMapperTest02.insert(name, age);
log.info("######insertUserResult:{}##########", insertUserResult);
// 怎么样验证事务开启成功!~
int i = 1 / age;
return insertUserResult;
} @Transactional()
public int insertUserTest01AndTest02(String name, Integer age) {
// 传统分布式事务解决方案 jta+atomikos 注册同一个全局事务中
// 第一个数据源
int insertUserResult01 = userMapperTest01.insert(name, age);
// 第二个数据源
int insertUserResult02 = userMapperTest02.insert(name, age);
int i = 1 / 0;
int result = insertUserResult01 + insertUserResult02;
// test01入库 test02回滚
return result;
} }
@Service
@Slf4j
public class UserServiceTest01 {
@Autowired
private UserMapperTest01 userMapperTest01; @Transactional(transactionManager = "test1TransactionManager")
public int insertUser(String name, Integer age) {
int insertUserResult = userMapperTest01.insert(name, age);
log.info("######insertUserResult:{}##########", insertUserResult);
int i = 1 / age;
// 怎么样验证事务开启成功!~
return insertUserResult;
} }

第三 多数据源分包方式事物

1、controller类

@RestController
public class MybatisMultilDataSourceController {
@Autowired
private UserServiceTest01 userServiceTest01;
@Autowired
private UserServiceTest02 userServiceTest02; @RequestMapping("/insertUserTest1")
public Integer insertUserTest1(String name, Integer age) {
return userServiceTest01.insertUser(name, age);
} @RequestMapping("/insertUserTest2")
public Integer insertUserTest2(String name, Integer age) {
return userServiceTest02.insertUser(name, age);
}
}

2、service类

根据包区分

@Service
@Slf4j
public class UserServiceTest01 {
@Autowired
private UserMapperTest01 userMapperTest01; @Transactional(transactionManager = "test1TransactionManager")
public int insertUser(String name, Integer age) {
int insertUserResult = userMapperTest01.insert(name, age);
log.info("######insertUserResult:{}##########", insertUserResult);
int i = 1 / age;
// 怎么样验证事务开启成功!~
return insertUserResult;
} }
@Service
@Slf4j
public class UserServiceTest02 {
@Autowired
private UserMapperTest02 userMapperTest02; @Transactional(transactionManager = "test2TransactionManager")
public int insertUser(String name, Integer age) {
int insertUserResult = userMapperTest02.insert(name, age);
log.info("######insertUserResult:{}##########", insertUserResult);
// 怎么样验证事务开启成功!~
int i = 1 / age;
return insertUserResult;
} }

3、mapper接口

根据包区分

public interface UserMapperTest01 {
// 查询语句
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name); // 添加
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
public interface UserMapperTest01 2{
// 查询语句
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name); // 添加
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}

4、创建多个数据源

@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.itmayiedu.test01", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config { @Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "test1SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// bean.setMapperLocations(
// new
// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
} @Bean(name = "test1TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test1SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.itmayiedu.test02", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config { @Bean(name = "test2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// bean.setMapperLocations(
// new
// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test2/*.xml"));
return bean.getObject();
} @Bean(name = "test2TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }

5、application.properties

###datasource1
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
spring.datasource.test1.password = root
###datasource2
spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
spring.datasource.test2.password = root

SpringBoot事物管理器的更多相关文章

  1. Spring事物管理--相关要点及配置事物管理器

    事务的四大特征 1.原子性:一个事务中所有对数据库的操作是一个不可分割的操作序列,要么全做要么全不做 2.一致性:数据不会因为事务的执行而遭到破坏 3.隔离性:一个事物的执行,不受其他事务的干扰,即并 ...

  2. SpringMVC 多个数据源 配置多个事物管理器 Multiple Transaction Managers

    http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction ...

  3. springboot数据库操作及事物管理操作例子

    一.配置文件 pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifa ...

  4. MyBatis6:MyBatis集成Spring事物管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...

  5. [原创]java WEB学习笔记109:Spring学习---spring中事物管理

    博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好 ...

  6. Spring中的事物管理,基于spring的bean的配置

    很多东西与上边的相同,这儿只简介: 导包... 数据库中建立三个表... 建立存放连接数据库的file文件:jdbc.properties: ----------------------------- ...

  7. Spring中的事物管理,用 @Transactional 注解声明式地管理事务

    事物: 事务管理是企业级应用程序开发中必不可少的技术,  用来确保数据的 完整性和 一致性. 事务就是一系列的动作, 它们被当做一个单独的工作单元. 这些动作要么全部完成, 要么全部不起作用 事务的四 ...

  8. 集成Spring事物管理

    什么是事物 事物是访问数据库的一个操作序列,数据库应用系统通过事物集来完成对数据库的存取.事物的正确执行使得数据库从一种状态转换为另一种状态. 事物必须服从ISO/IEC所制定的ACID原则.ACID ...

  9. Spring学习之声明式事物管理

    public List<Student> selectStudent() { Student s = new Student(); s.setName("zhengbin&quo ...

随机推荐

  1. 【Random Forest】林轩田机器学习技法

    总体来说,林对于random forest的讲解主要是算法概况上的:某种程度上说,更注重insights. 林分别列举了Bagging和Decision Tree的各自特点: Random Fores ...

  2. 常见数据结构图文详解-C++版

    目录 简介 一.数组 1. 静态数组 array 2. 动态数组 2.1. vector 2.2. priority_queue 2.3. deque 2.4. stack 2.5. queue二.单 ...

  3. Numpy 与 DataFrame对比与应用

    (一)对比Numpty 与 DataFrame默认索引取值不同点 Numpy索引取值 #Numpy索引取值 data=np.empty((2,4),dtype=int) print(data) ''' ...

  4. __PRETTY_FUNCTION__,__func__,__FUNCTION__

    今天在看苹果的官方demo的时候,发现这个打印调用方法的参数,很是好奇,遂bing了一番. NSLog(@"----------------%s",__PRETTY_FUNCTIO ...

  5. URAL 1944 大水题模拟

    D - Record of the Attack at the Orbit Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format ...

  6. Java8并行流使用注意事项

    对于从事Java开发的童鞋来说,相信对于Java8的并行流并不陌生,没错,我们常常用它来执行并行任务,但是由于并行流(parallel stream)采用的是享线程池,可能会对我们的性能造成严重影响, ...

  7. CORS跨域cookie传递

    服务端 Access-Control-Allow-Credentials:true Access-Control-Allow-Methods:* Access-Control-Allow-Origin ...

  8. html li css选中状态切换

    思路:点击当前li元素后是用removeClass()删除所有兄弟元素(使用siblings()获取)的class样式,然后使用addClass()为当前li添加class. 具体演示如下: 1.HT ...

  9. 8.2 前端检索的敏感词过滤的Python实现(针对元搜索)

    对于前端的搜索内容进行控制,比如敏感词过滤,同样使用socket,这里使用Python语言做一个demo.这里不得不感叹一句,socket真是太神奇了,可以跨语言把功能封装,为前端提供服务. 下面就是 ...

  10. js判断中出现两个!!是什么意思?

    在js中看源码时有时候出现两个!!,我起初以为是js的其他语法,其实!!就是两次取“非”的运算. 下面证明我的说法. alert(null);//false alert(!null);//true a ...