1.创建一个maven项目,导入相关配置:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.royal</groupId>
<artifactId>springBoot</artifactId>
<version>1.0-SNAPSHOT</version> <name>springBoot</name> <!--父依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency> <!-- mybaties -->
<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> <!--jta管理多个数据源事务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties> <build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build> </project>

pom.xml

2.配置数据连接配置

1)创建两个数据库(test1和test2),然后创建测试的表

use test1;
CREATE table user(
id int PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
password VARCHAR(50),
email VARCHAR(50),
birthday TIMESTAMP
); use test2;
CREATE table customer(
id int PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
tel VARCHAR(50)
);

sql

2)在application.properties文件里面添加数据库连接参数

#数据库配置
# Mysql 1
mysql.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
mysql.datasource.test1.username = root
mysql.datasource.test1.password = 123456 mysql.datasource.test1.minPoolSize = 3
mysql.datasource.test1.maxPoolSize = 25
mysql.datasource.test1.maxLifetime = 20000
mysql.datasource.test1.borrowConnectionTimeout = 30
mysql.datasource.test1.loginTimeout = 30
mysql.datasource.test1.maintenanceInterval = 60
mysql.datasource.test1.maxIdleTime = 60 mysql.datasource.test1.testQuery = select 1 # Mysql 2
mysql.datasource.test2.url =jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
mysql.datasource.test2.username =root
mysql.datasource.test2.password =123456 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

application.properties

3)添加两个配置模型

  模型放在com.royal.dbconfig

@ConfigurationProperties("mysql.datasource.test1")
public class DBConfig1 {
private String url;
private String username;
private String password;
private int minPoolSize;
private int maxPoolSize;
private int maxLifetime;
private int borrowConnectionTimeout;
private int loginTimeout;
private int maintenanceInterval;
private int maxIdleTime;
private String testQuery;
//........省略get和set方法.....
}
@ConfigurationProperties("mysql.datasource.test2")
public class DBConfig2 {
private String url;
private String username;
private String password;
private int minPoolSize;
private int maxPoolSize;
private int maxLifetime;
private int borrowConnectionTimeout;
private int loginTimeout;
private int maintenanceInterval;
private int maxIdleTime;
private String testQuery;
//........省略get和set方法.....
}

4)数据源配置

package com.royal.datasource;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.royal.dbconfig.DBConfig1;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource; @Configuration//注解到springboot容器中
@MapperScan(basePackages="com.royal.test1.mapper",sqlSessionFactoryRef="test1SqlSessionFactory")
public class DataSource01 { // 配置数据源
@Primary
@Bean(name = "test1DataSource")
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("test1DataSource"); 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 = "test1SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name = "test1SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

test2的数据源一样,把test1改成test2

3.创建mapper与service,并写一个Controller进行测试

package com.royal.test1.service;

import com.royal.model.User;
import com.royal.test1.mapper.UserMapper;
import com.royal.test2.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
@Transactional
public class UserService{ @Autowired
private UserMapper userMapper; @Autowired
private CustomerMapper customerMapper;
public void register(String name) { customerMapper.insert(name,"123");
userMapper.save(name,"123"); } }

mapper

package com.royal.test1.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param; public interface UserMapper {
@Insert("insert into user(username,password) values(#{username},#{password})")
public int save(@Param("username") String username, @Param("password") String password);
}
package com.royal.test2.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param; public interface CustomerMapper {
@Insert("insert into customer(name,tel) values(#{name},#{tel})")
public int insert(@Param("name") String name, @Param("tel") String tel);
}

Controller

package com.royal.Web.Controller;

import com.royal.test1.service.UserSerivce;
import com.royal.test2.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("user")
public class UserController { @Autowired
private UserSerivce userSerivce; @RequestMapping("add/{name}")
@ResponseBody
public String add(@PathVariable() String name){
userSerivce.register(name);
return "success";
}
}

Controller

4.Main方法

package com.royal;

import com.royal.dbconfig.DBConfig1;
import com.royal.dbconfig.DBConfig2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan; @ComponentScan(basePackages = "com.royal")
@EnableAutoConfiguration
@EnableConfigurationProperties(value = {DBConfig1.class, DBConfig2.class})
public class App{
public static void main( String[] args )
{
SpringApplication.run(App.class,args);
}
}

springboot多数据源+jta事务管理配置的更多相关文章

  1. JTA事务管理--配置剖析(二)

    Spring引用Tomcat的 JTA事务     Tomcat是Servlet容器,但它提供了JNDI的实现,因此用户可以象在Java EE应用程序服务器中一样,在Tomcat中使用JNDI查找JD ...

  2. JTA事务管理--配置剖析

    概述    [IT168 专稿]Spring 通过AOP技术可以让我们在脱离EJB的情况下享受声明式事务的丰盛大餐,脱离Java EE应用服务器使用声明式事务的道路已经畅通无阻.但是很大部分人都还认为 ...

  3. spring,mybatis事务管理配置与@Transactional注解使用[转]

    spring,mybatis事务管理配置与@Transactional注解使用[转] spring,mybatis事务管理配置与@Transactional注解使用 概述事务管理对于企业应用来说是至关 ...

  4. JTA事务管理

    何为分布式事务 一个事务包含多个操作,多个操作操作了多个数据源,这样的事务称为分布式事务 和普通事务的区别 单一数据源,事务管理可以借助数据源本地事务完成,实现简单 分布式事务之困难:不可简单的借助数 ...

  5. 事务管理配置与@Transactional注解使用

    spring,mybatis事务管理配置与@Transactional注解使用 概述 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性. Spring Framewor ...

  6. spring,mybatis事务管理配置与@Transactional注解使用

    spring,mybatis事务管理配置与@Transactional注解使用[转]   spring,mybatis事务管理配置与@Transactional注解使用 概述事务管理对于企业应用来说是 ...

  7. Spring事务管理配置以及异常处理

    Spring事务管理配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=" ...

  8. Spring Boot 2.x基础教程:使用JTA实现多数据源的事务管理

    在一个Spring Boot项目中,连接多个数据源还是比较常见的.之前也介绍了如何在几种常用框架的场景下配置多数据源,具体可见: Spring Boot 2.x基础教程:JdbcTemplate的多数 ...

  9. SpringBoot 集成MyBatis、事务管理

    集成MyBatis (1)在pom.xml中添加依赖 <!-- mybatis的起步依赖.包含了mybatis.mybatis-spring.spring-jdbc(事务要用到)的坐标 --&g ...

随机推荐

  1. AttributeError: 'list' object has no attribute 'data'智障错误

    import urllib.requestimport urllib.parse url = ['http://fanyi.youdao.com/translate?smartresult=dict& ...

  2. SDN(Software Defined Network):软件定义网络----转载

    SDN(Software Defined Network):软件定义网络 传统的网络转发行为: 1)逐设备单独控制,纯分布式控制. 2)控制面和转发面在同一个设备中,耦合紧密. 管理员无法直接操控转发 ...

  3. day25(025-多线程(下)&GUI)

    线程状态图 ###25.01_多线程(单例设计模式)(掌握) 单例设计模式:保证类在内存中只有一个对象. 如何保证类在内存中只有一个对象呢? (1)控制类的创建,不让其他类来创建本类的对象.priva ...

  4. React之Redux知识点补充

    一. reducer纯函数方便自动化测试 二.

  5. java 实现每次从list中取5000条数据放入新list

    从list中取固定条数的数据放入新的list里 public static <T> List<List<T>> split(List<T> resLis ...

  6. Arduino Wireless Communication – NRF24L01 Tutorial(arduino无线通信---NRF24L01教程)

    arduino下nrf24l01库文件及相关说明 库的说明文档 https://tmrh20.github.io/RF24/ 库的源代码github下载页面 https://tmrh20.github ...

  7. http与socket

    http是一个应用层的协议 socket不是一个协议,而是一个编程(API)接口

  8. MySQL-TPS,QPS到底是什么

    计算TPS,QPS的方式 qps,tps是衡量数据库性能的关键指标,网上普遍有两种计算方式 TPS,QPS相关概念 QPS:Queries Per Second         查询量/秒,是一台服务 ...

  9. 201771010123汪慧和《面向对象程序设计JAVA》第八周实验总结

    一.理论部分 1.接口 用interface声明,是抽象方法和常量值定义的集 合.从本质上讲,接口是一种特殊的抽象类. 在Java程序设计语言中,接口不是类,而是对类 的一组需求描述,由常量和一组抽象 ...

  10. slam库安装

    Ceres安装: 1.Ceres是一个cmak工程,首先要安装他的依赖项,使用apt-get安装. sudo apt-get install liblapack-dev libsuitesparse- ...