springboot之多数据源

这是一个简单的springboot+mybatis配置多数据源demo。这个demo存在的问题是:每个数据源都匹配了事务管理器(其中一个事务管理器设置了@Primary 否则会报单例错误),所以执行时只有配置了@Primary的事务起作用,其他数据源的事务没作用。
项目结构
在这里插入图片描述
pom.xml配置

<?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.ldg</groupId>
    <artifactId>springboot_02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springboot_02 Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>
    <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>
    <!--父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- SpringBoot 核心组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- mybaties -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>springboot_02</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <!--扫描java下的所有.xml文件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

application.properties配置
application.properties的加载:
springboot加载的配置文件是放在environment中的,prepareEnvironment的时候,springboot读取和加载了application.properties文件

#jsp前后缀
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
server.port=10002
#单个数据库连接信息
#spring.datasource.url=jdbc:mysql://localhost:3306/springboot
#spring.datasource.username=root
#spring.datasource.password=714838871
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#数据库springboot
spring.datasource.springboot.driverClassName=com.mysql.jdbc.Driver
spring.datasource.springboot.url=jdbc:mysql:///springboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.springboot.username=ldg
spring.datasource.springboot.password=714838871
#数据库springboottest01
spring.datasource.springboottest01.driverClassName=com.mysql.jdbc.Driver
spring.datasource.springboottest01.url=jdbc:mysql:///springboottest01?useUnicode=true&characterEncoding=utf-8
spring.datasource.springboottest01.username=ldg
spring.datasource.springboottest01.password=714838871


Datasource01
@primary 写在这里

package com.ldg.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 javax.sql.DataSource;

//springboot的数据源配置

// 注解到springboot容器中 会将被@bean注解的方法生成对应bean 放入springboot容器中
@Configuration
//扫描关联springboot数据源的接口和mapper.xml文件
@MapperScan(basePackages = "com.ldg.mapper", sqlSessionFactoryRef ="sqlsessionfactory")
public class DataSource01 {
    /**
     * @return 返回springboot数据库的数据源
     */
    @Bean(name ="datasource")
    @Primary//主数据源
    @ConfigurationProperties(prefix = "spring.datasource.springboot")
    public DataSource dateSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * @return 返回springboot数据库的会话工厂
     */
    //@Qualifier 会按id找bean
    @Bean(name="sqlsessionfactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource") DataSource ds) throws Exception {
        //声明sqlsession工厂bean
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);

        return bean.getObject();
    }

    /**
     * @return 返回springboot数据库的事务
     */
    @Bean(name = "transactionManager")
    //主键 会以该事务管理器为主
    @Primary
    //@Qualifier 会按id找bean
    public DataSourceTransactionManager transactionManager(@Qualifier("datasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * @return 返回springboot数据库的会话模版
     */
    @Bean(name = "SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("sqlsessionfactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}




Datasource02

package com.ldg.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 javax.sql.DataSource;

//springboot的数据源配置

// 注解到springboot容器中 会将被@bean注解的方法生成对应bean 放入springboot容器中
@Configuration
//扫描关联springboot数据源的接口和mapper.xml文件
@MapperScan(basePackages = "com.ldg.mapper02", sqlSessionFactoryRef ="sqlsessionfactory02")
public class DataSource02 {
    /**
     * @return 返回springboot数据库的数据源
     */
    @Bean(name ="datasource02")

    @ConfigurationProperties(prefix = "spring.datasource.springboottest01")
    public DataSource dateSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * @return 返回springboot数据库的会话工厂
     */
    //@Qualifier 会按id找bean
    @Bean(name="sqlsessionfactory02")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource02") DataSource ds) throws Exception {
        //声明sqlsession工厂bean
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);

        return bean.getObject();
    }

    /**
     * @return 返回springboot数据库的事务
     */
    @Bean(name ="transactionManager02")
    //@Qualifier 会按id找bean
    public DataSourceTransactionManager transactionManager(@Qualifier("datasource02") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * @return 返回springboot数据库的会话模版
     */
    @Bean(name = "SqlSessionTemplate02")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("sqlsessionfactory02") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}




IUserMapper:

package com.ldg.mapper;

import com.ldg.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface IUserMapper {
    //注解配置
    //会自动与注解生成代理
//    @Insert("insert  test  values(#{username},#{password})")
//    public void save(@Param("username") String username, @Param("password") String password);
//
//    @Select("select *  from  test  where username=#{a}")
//    public User foundUser(@Param("a") String username);

    public void save(String username, String password);

    public User foundUser(String username);
}

IUserMapper.xml


```java
<?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.ldg.mapper.IUserMapper" >
    <insert id="save">
        insert into test (username,password) VALUES(#{0},#{1})
    </insert>
    <select id="foundUser" resultType="com.ldg.model.User" parameterType="string">
        select * from test where username = #{username}
    </select>
</mapper>

UserServiceImp:

```java
package com.ldg.service.imp;

import com.ldg.mapper.IUserMapper;
import com.ldg.model.User;
import com.ldg.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//操作springboot数据库的服务
@Service("test01")
@Transactional
public class UserServiceImp2 implements IUserService {
    //会自动注入生成的代理对象 关联springboot
    @Autowired
    private IUserMapper iUserMapper;

    @Override
    public void save(String username, String password) {
        iUserMapper.save(username, password);
         int i=10/0;

    }

    @Override
    public User foundUser(String username) {

        return iUserMapper.foundUser(username);
    }
}

UserController:

package com.ldg.web.controller;

import com.ldg.model.User;
import com.ldg.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.context.annotation.ComponentScan;
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("/test")
public class UserController {
    @Autowired
    @Qualifier("test01")
    private IUserService iUserService;

    @RequestMapping("/one")
    public String test() {
        return "one";
    }

    @RequestMapping("/save/{username}/{password}")
    public String save(@PathVariable String username, @PathVariable String password) {
        iUserService.save(username, password);
        return "success";
    }

    @RequestMapping("/get/{username}")
    @ResponseBody
    public User get(@PathVariable String username) {
        return iUserService.foundUser(username);
}

    @RequestMapping("/savetwo/{username}/{password}")
    public String saveTwo(@PathVariable String username, @PathVariable String password) {
        iUserService.save(username, password);
        return "success";
    }

    @RequestMapping("/gettwo/{username}")
    @ResponseBody
    public User getTwo(@PathVariable String username) {
        return iUserService.foundUser(username);
    }
}

其他的代码类似。

App:

import com.ldg.web.controller.UserController;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

//@MapperScan(basePackages = "com.ldg.mapper")
@ComponentScan(basePackages = {"com.ldg.service", "com.ldg.web","com.ldg.datasource"})
@EnableAutoConfiguration
public class App {

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);


    }
}

有些重复代码就省略了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值