• springBoot整合mybatis多数据源,支持分布式事务


    编码工具:IDEA

    SpringBoot版本:2.0.1

    JDK版本:1.8

    1.使用IDEA构建一个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.wuzz.demo</groupId>
        <artifactId>spring-boot-jdbc</artifactId>
        <version>1.0-SNAPSHOT</version>
    
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <parent>
    
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.0.1.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.1</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webflux</artifactId>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>io.projectreactor</groupId>
                <artifactId>reactor-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>com.zaxxer</groupId>
                <artifactId>HikariCP</artifactId>
                <version>3.2.0</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jta-atomikos -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jta-atomikos</artifactId>
            </dependency>
    
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2.添加启动类:

    @SpringBootApplication
    public class App {
    
        public static void main( String[] args )
        {
            SpringApplication.run(App.class, args);
        }
    }
    

    3.数据源配置:MasterDataSourceConfig

    @Configuration
    @MapperScan(basePackages = "com.wuzz.demo.mapper.mapper1", sqlSessionFactoryRef = "masterSqlSessionFactory")
    public class MasterDataSourceConfig {
    
        @Bean(name = "masterDataSource")
        @Primary
        public DataSource masterDataSource(){
    
    //        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    //
    //        DataSource dataSource = dataSourceBuilder
    //                .driverClassName("com.mysql.jdbc.Driver")
    //                .url("jdbc:mysql://localhost:3306/disaster")
    //                .username("root")
    //                .password("zhenzhao123456")
    //                .build();
    //
    //        return dataSource;
            MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
            mysqlXaDataSource.setUrl("jdbc:mysql://localhost:3306/disaster?useSSL=true");
            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
            mysqlXaDataSource.setPassword("zhenzhao123456");
            mysqlXaDataSource.setUser("root");
            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
    
            AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
            xaDataSource.setXaDataSource(mysqlXaDataSource);
            xaDataSource.setUniqueResourceName("masterDataSource");
    
            return xaDataSource;
        }
    
        @Bean(name = "masterSqlSessionFactory")
        @Primary
        public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/master.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "masterSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

      SlaveDataSourceConfig:

    @Configuration
    @MapperScan(basePackages = "com.wuzz.demo.mapper.mapper2", sqlSessionFactoryRef = "slaveSqlSessionFactory")
    public class SlaveDataSourceConfig {
    
        @Bean(name = "salveDataSource")
        public DataSource salveDataSource(){
    
    //        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    //
    //        DataSource dataSource = dataSourceBuilder
    //                .driverClassName("com.mysql.jdbc.Driver")
    //                .url("jdbc:mysql://localhost:3306/study?useSSL=true")
    //                .username("root")
    //                .password("zhenzhao123456")
    //                .build();
    //
    //        return dataSource;
            MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
            mysqlXaDataSource.setUrl("jdbc:mysql://localhost:3306/study");
            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
            mysqlXaDataSource.setPassword("zhenzhao123456");
            mysqlXaDataSource.setUser("root");
            mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
    
            AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
            xaDataSource.setXaDataSource(mysqlXaDataSource);
            xaDataSource.setUniqueResourceName("salveDataSource");
    
            return xaDataSource;
    
        }
        @Bean(name = "slaveSqlSessionFactory")
        public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("salveDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/slave.xml"));
            return bean.getObject();
        }
    
        @Bean(name = "slaveSqlSessionTemplate")
        public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

    4.配置相应的Mapper接口类及XML:

    public interface UserMapper1 {
    
        int insert(User user);
    
    }
    public interface UserMapper2 {
    
        int insert(User user);
    
    }
    

      XML:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.wuzz.demo.mapper.mapper1.UserMapper1" >
        <resultMap id="BaseResultMap" type="com.wuzz.demo.domain.User" >
            <id column="id" property="id" jdbcType="BIGINT" />
            <result column="name" property="name" jdbcType="VARCHAR" />
        </resultMap>
    
        <insert id="insert" parameterType="com.wuzz.demo.domain.User" >
           INSERT INTO
                user
                (id,name)
            VALUES
                (#{id}, #{name})
        </insert>
    </mapper>
    ================================================
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.wuzz.demo.mapper.mapper2.UserMapper2" >
        <resultMap id="BaseResultMap" type="com.wuzz.demo.domain.User" >
            <id column="id" property="id" jdbcType="BIGINT" />
            <result column="name" property="name" jdbcType="VARCHAR" />
        </resultMap>
    
        <insert id="insert" parameterType="com.wuzz.demo.domain.User" >
           INSERT INTO
                user
                (id,name)
            VALUES
                (#{id}, #{name})
        </insert>
    </mapper>
    

    5.service层编写:

    @Service
    public class UserServiceImpl implements com.wuzz.demo.service.impl.UserService {
    
        @Autowired
        private UserMapper1 userMapper1;
    
        @Autowired
        private UserMapper2 userMapper2;
    
        @Override
        @Transactional
        public int insert(User user) {
            userMapper1.insert(user);
    
            userMapper2.insert(user);
            int k =1/0;
    
            return 1;
        }
    }

    6.controller:

    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @PostMapping("/web/mvc/user/save")
        public int save(@RequestBody User user) throws ExecutionException, InterruptedException {
    
            return  userService.insert(user);
        }
    }
    

      最后启动 SpringBoot 。测试完成。

  • 相关阅读:
    [原创]软件性能测试培训
    100w条记录分页,可以有多快?—— DataReader分页与SQL语句分页的对比测试(在线演示)
    【自然框架】注册会员活动——第一份代码的修改建议(第一版)
    加班有几种情况?兼谈讨论的方式。
    衔着树枝飞跃太平洋的傻鸟!(童话版)
    参加活动的好处。
    【自然框架】开源社区活动,会员注册的第一份代码!
    【自然框架】数据访问之精雕细琢(一)存储过程的参数
    自然框架开发系列(一):自然框架 和 AgileEAS.NET 合作,开发b/s的药店系统!
    自然框架开源社区的第一次活动——实现会员注册
  • 原文地址:https://www.cnblogs.com/wuzhenzhao/p/10315130.html
Copyright © 2020-2023  润新知