spring boot使用多数据源体验


 小白是一名.net程序员,之前小白介绍了过了自己的博客系统http://www.ttblog.site/,用.net写厌了,所以想学下java尝尝鲜,于是小白准备用spring boot来实现一个博客内容管理系统。

    因为管理系统要有自己的数据源,但是又要从博客系统获取博客内容,所以第一反应是要弄一个多数据源,因为没有java开发实战基础,所以都是从网上百度的,这里只是把自己的过程分享出来。

   配置数据源:

spring.datasource.data-blog.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.data-blog.username=
spring.datasource.data-blog.password=
spring.datasource.data-blog.jdbc-url=jdbc:mysql://127.0.0.1:3306/Blog?characterEncoding=utf8&useSSL=false&serverTimezone=UTC

spring.datasource.data-cms.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.data-cms.username=
spring.datasource.data-cms.password=
spring.datasource.data-cms.jdbc-url=jdbc:mysql://127.0.0.1:3306/CMS?characterEncoding=utf8&useSSL=false&serverTimezon

   注意:之前我写的是 spring.datasource.data-cms.url,但是出现“jdbcUrl is required with driverClassName”错误,于是百度得到结果为替换成jdbc-url:https://blog.csdn.net/qq_40437152/article/details/90905336

   创建数据配置:

package com.blog.cms.properties;

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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.blog.cms.dao.b",sqlSessionFactoryRef = "blogSqlsessionFactory")
public class DataSourceBLOG {
    /**
     * 返回数据源
     * @return
     */
    @Bean(name = "blogDataSoruce")
    @ConfigurationProperties(prefix="spring.datasource.data-blog")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 返回数据库会话工厂
     * @return
     */
    @Bean(name = "blogSqlsessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("blogDataSoruce")DataSource dataSource) throws  Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/b/**/*Mapper.xml"));
        return  bean.getObject();
    }

    /**
     * 返回数据库会话模板
     * @return
     */
    @Bean(name = "blogSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("blogSqlsessionFactory")SqlSessionFactory factory){
        return  new SqlSessionTemplate(factory);
    }
    /**
     * 返回数据库的事务
     * @param dataSource
     * @return
     */
    @Bean(name = "blogTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("blogDataSoruce") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 返回jdbc
     * @param dataSource
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("blogDataSoruce") DataSource dataSource){
        return  new JdbcTemplate(dataSource);
    
package com.blog.cms.properties;

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.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.blog.cms.dao.c",sqlSessionFactoryRef = "cmsSqlsessionFactory")
public class DataSourceCMS {
    /**
     * 返回数据源
     * @return
     */
    @Bean(name = "cmsDataSoruce")
    @ConfigurationProperties(prefix="spring.datasource.data-cms")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 返回数据库会话工厂
     * @return
     */
    @Bean(name = "cmsSqlsessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("cmsDataSoruce")DataSource dataSource) throws  Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/c/**/*Mapper.xml"));
        return  bean.getObject();
    }

    /**
     * 返回数据库会话模板
     * @return
     */
    @Bean(name = "cmsSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("cmsSqlsessionFactory")SqlSessionFactory factory){
        return  new SqlSessionTemplate(factory);
    }
    /**
     * 返回数据库的事务
     * @param ds
     * @return
     */
    @Bean(name = "cmsTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("cmsDataSoruce") DataSource ds){
        return new DataSourceTransactionManager(ds);
    }
    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<String> selectTables(String dataBaseName) {
         String sql="select table_name from information_schema.tables where table_schema=?";
         try {
             List<String> list= jdbcTemplate.queryForList(sql,String.class,dataBaseName);
             return list;
         }
         catch (Exception ex)
         {
             return null;
         }

    }

 注意:如果你不需要使用原生jdbc,则不需要最后一个方法,我这里是需要。并且要加上“bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/b/**/*Mapper.xml"));”,我网上查的是有的人没加,但是我不加的话一直提示找不到select节点的错误。

启动类:

@SpringBootApplication(scanBasePackages = {"com.blog.cms", "com.blog.cms.web"})
@EnableScheduling
@ServletComponentScan
@EnableTransactionManagement(proxyTargetClass = true)
public class AdminWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdminWebApplication.class, args);
    }

}

我的代码结构如图,每个数据源所对应的mapper和xml都要分开:

 

目前到现在,我已是能够正常的运行项目了,但是目前还不知道配置数据源的地方那几个注解的作用,准备去把它搞懂。总的感觉会.net再学java觉得很轻松,大部分都是类似的。

转自:http://www.ttblog.site


作者:灬丶,发布于:2020/06/30
原文:https://www.cnblogs.com/MrHanBlog/p/13210556.html