【Java】SpringBoot整合多数据源JdbcTemplate、Mybatis、Jpa

2023-05-16

SpringBoot 整合 JdbcTemplate 多数据源

pom

<!--        引入阿里的数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>

application.properties

#快捷键alt拉动一列添加one,此时自动配置失效
#数据源one
spring.datasource.one.url=jdbc:mysql://localhost:3306/db_jdbctemplate
spring.datasource.one.username=root
spring.datasource.one.password=rootroot
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
#数据源two
spring.datasource.two.url=jdbc:mysql://localhost:3306/db_jdbctemplate2
spring.datasource.two.username=root
spring.datasource.two.password=rootroot
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
  • config

DataSourceConfig.java

package com.bennyrhys.jdbctemplate2.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 指定配置文件对应的不同数据源
 */
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dsOne(){
        return DruidDataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo(){
        return DruidDataSourceBuilder.create().build();
    }
}

JdbcTemplateConfig.java

package com.bennyrhys.jdbctemplate2.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class JdbcTemplateConfig {
    //@Qualifier("dsOne")指明要注入的bean,后面的参数名无所谓
    @Bean
    JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dsOne){
        return new JdbcTemplate(dsOne);
    }
    @Bean
    JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dsTwo){
        return new JdbcTemplate(dsTwo);
    }
}
  • bean
public class User {
    private Integer id;
    private String username;
    private String address;
  • test
package com.bennyrhys.jdbctemplate2;

import com.bennyrhys.jdbctemplate2.bean.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest
class  Jdbctemplate2ApplicationTests {
    @Autowired //是按照类型查找的,但现在有两个template类型(会报错,需要结合)
    @Qualifier("jdbcTemplateOne")
    JdbcTemplate jdbcTemplateOne;

    @Resource(name = "jdbcTemplateTwo")
    JdbcTemplate jdbcTemplateTwo;

    @Test
    void contextLoads() {
        List<User> list1 = jdbcTemplateOne.query("select * from user", new BeanPropertyRowMapper<>(User.class));
        System.out.println(list1);
        List<User> list2 = jdbcTemplateTwo.query("select * from user", new BeanPropertyRowMapper<>(User.class));
        System.out.println(list2);

    }

}

控制台输出:

[User{id=2, username=‘bennyrhys’, address=‘jilin’}, User{id=3, username=‘bennyrhys’, address=‘lanzou’}]
2020-01-19 22:39:03.408 INFO 6114 — [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
[User{id=1, username=‘zhangsan’, address=‘通化’}]

SpringBoot整合Mybatis多数据源

现在很少用,一般用中间件MyCat整合或者jdbctemplate的同源

pom.xml

<!--修改版本信息-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.16</version>
        </dependency>
<!--        引入阿里数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

application.properties

#数据源1
spring.datasource.one.url=jdbc:mysql://localhost:3306/db_jdbctemplate
spring.datasource.one.username=root
spring.datasource.one.password=rootroot
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
#数据源2
spring.datasource.two.url=jdbc:mysql://localhost:3306/db_jdbctemplate2
spring.datasource.two.username=root
spring.datasource.two.password=rootroot
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

com.bennyrhys.mybatis2.bean.User

public class User {    private Integer id;    private String username;    private String address;
  • config

DataSourceConfig.java

package com.bennyrhys.mybatis2.config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;/** * 数据源的配置 */@Configurationpublic class DataSourceConfig {    @Bean    @ConfigurationProperties(prefix = "spring.datasource.one")    DataSource dsOne(){        return DruidDataSourceBuilder.create().build();    }    @Bean    @ConfigurationProperties(prefix = "spring.datasource.two")    DataSource dsTwo(){        return DruidDataSourceBuilder.create().build();    }}

MyBatisConfigOne.java

package com.bennyrhys.mybatis2.config;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.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;import javax.sql.DataSource;@Configuration@MapperScan(basePackages = "com.bennyrhys.mybatis2.mapper1", sqlSessionFactoryRef = "sqlSessionFactory1", sqlSessionTemplateRef = "sessionTemplate1")public class MyBatisConfigOne {    @Resource(name = "dsOne")    DataSource dsOne;    @Bean    SqlSessionFactory sqlSessionFactory1(){        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();        try {            bean.setDataSource(dsOne);            return bean.getObject();        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    @Bean    SqlSessionTemplate sessionTemplate1(){        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1());        return template;    }}

MyBatisConfigTwo.java

package com.bennyrhys.mybatis2.config;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.bennyrhys.mybatis2.mapper2", sqlSessionFactoryRef = "sqlSessionFactory2", sqlSessionTemplateRef = "sessionTemplate2")
public class MyBatisConfigTwo {
    @Resource(name = "dsTwo")
    DataSource dsTwo;

    @Bean
    SqlSessionFactory sqlSessionFactory2(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        try {
            bean.setDataSource(dsTwo);
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Bean
    SqlSessionTemplate sessionTemplate2(){
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
        return template;
    }

}
  • mapper1

UserMapper1.java

package com.bennyrhys.mybatis2.mapper1;

import com.bennyrhys.mybatis2.bean.User;

import java.util.List;

public interface UserMapper1 {
    List<User> getAllUsers();
}

UserMapper1.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.bennyrhys.mybatis2.mapper1.UserMapper1">    <select id="getAllUsers" resultType="com.bennyrhys.mybatis2.bean.User">        select * from user;    </select></mapper>
  • mapper2

UserMapper2

package com.bennyrhys.mybatis2.mapper2;

import com.bennyrhys.mybatis2.bean.User;

import java.util.List;

public interface UserMapper2 {
    List<User> getAllUser();
}

UserMapper2.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.bennyrhys.mybatis2.mapper2.UserMapper2">
    <select id="getAllUser" resultType="com.bennyrhys.mybatis2.bean.User">
        select * from user;
    </select>
</mapper>

Pom.xml 修改访问路径

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes><include>**/*.xml</include></includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>

test

package com.bennyrhys.mybatis2;

import com.bennyrhys.mybatis2.bean.User;
import com.bennyrhys.mybatis2.mapper1.UserMapper1;
import com.bennyrhys.mybatis2.mapper2.UserMapper2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class Mybatis2ApplicationTests {
    @Autowired
    UserMapper1 userMapper1;
    @Autowired
    UserMapper2 userMapper2;

//记得启动之前,要声明mapper.xml位置,pom中定义

    /**
     * [User{id=2, username='bennyrhys', address='jilin'}, User{id=3, username='bennyrhys', address='lanzou'}]
     * 2020-01-20 13:30:35.558  INFO 1927 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} inited
     * [User{id=1, username='zhangsan', address='通化'}]
      */
    @Test
    void contextLoads() {
        List<User> list1 = userMapper1.getAllUsers();
        System.out.println(list1);

        List<User> list2 = userMapper2.getAllUser();
        System.out.println(list2);
    }

}

SpringBoot整合Jpa多数据源

模板选择web、mysql driver、jpa

pom.xml

<!--修改mysql版本-->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <scope>runtime</scope>            <version>8.0.16</version>        </dependency><!--        添加阿里数据源-->        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid-spring-boot-starter</artifactId>            <version>1.1.10</version>        </dependency>

application.properties

#配置数据源spring.datasource.one.url=jdbc:mysql://localhost:3306/db_jdbctemplatespring.datasource.one.username=rootspring.datasource.one.password=rootrootspring.datasource.one.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.two.url=jdbc:mysql://localhost:3306/db_jdbctemplate2spring.datasource.two.username=rootspring.datasource.two.password=rootrootspring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource#配置jpa,前面配置定义了propertiesspring.jpa.properties.show-sql=truespring.jpa.properties.hibernate.ddl-auto=updatespring.jpa.properties.database=mysqlspring.jpa.properties.database-platform=mysqlspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

Book

@Entity(name = "t_book")public class Book {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Integer id;    private String name;    private String author;
  • config

DataSourceConfig

package com.bennyrhys.jpa2.config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;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 javax.sql.DataSource;@Configurationpublic class DataSourceConfig {    @Bean    @Primary //优先使用,特色    @ConfigurationProperties(prefix = "spring.datasource.one")    DataSource dsOne(){        return  DruidDataSourceBuilder.create().build();    }    @Bean    @ConfigurationProperties(prefix = "spring.datasource.two")    DataSource dsTwo(){        return  DruidDataSourceBuilder.create().build();    }}

JpaConfig1

package com.bennyrhys.jpa2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
//JPA相关扫描dao
@EnableJpaRepositories(basePackages = "com.bennyrhys.jpa2.dao1",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBean1",
        transactionManagerRef = "platformTransactionManager1")
public class JpaConfig1 {
    @Autowired
    @Qualifier("dsOne")
    DataSource dsOne;

    @Autowired  //加载properties的jpa
    JpaProperties jpaProperties;

    @Bean
    @Primary //多实例,优先使用
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean1(EntityManagerFactoryBuilder builder){
        return builder.dataSource(dsOne)
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu1")
                .packages("com.bennyrhys.jpa2.bean")
                .build();
    }
//    事务
    @Bean
    PlatformTransactionManager platformTransactionManager1(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean1(builder).getObject());
    }
}

JpaConfig2

package com.bennyrhys.jpa2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
//JPA相关扫描dao
@EnableJpaRepositories(basePackages = "com.bennyrhys.jpa2.dao2",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBean2",
        transactionManagerRef = "platformTransactionManager2")
public class JpaConfig2 {
    @Autowired
    @Qualifier("dsTwo")
    DataSource dsTwo;

    @Autowired  //加载properties的jpa
    JpaProperties jpaProperties;

    @Bean
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean2(EntityManagerFactoryBuilder builder){
        return builder.dataSource(dsTwo)
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu2")
                .packages("com.bennyrhys.jpa2.bean")
                .build();
    }
//    事务
    @Bean
    PlatformTransactionManager platformTransactionManager2(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean2(builder).getObject());
    }
}
  • dao1

BookDao1

package com.bennyrhys.jpa2.dao1;

import com.bennyrhys.jpa2.bean.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookDao1 extends JpaRepository<Book,Integer> {
}
  • dao2

BookDao2

package com.bennyrhys.jpa2.dao2;

import com.bennyrhys.jpa2.bean.Book;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookDao2 extends JpaRepository<Book,Integer> {
}

Test

package com.bennyrhys.jpa2;

import com.bennyrhys.jpa2.bean.Book;
import com.bennyrhys.jpa2.dao1.BookDao1;
import com.bennyrhys.jpa2.dao2.BookDao2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class Jpa2ApplicationTests {
    @Autowired
    BookDao1 dao1;
    @Autowired
    BookDao2 dao2;

    @Test
    void contextLoads() {
        List<Book> all = dao1.findAll();
        System.out.println(all);
        List<Book> all1 = dao2.findAll();
        System.out.println(all1);
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【Java】SpringBoot整合多数据源JdbcTemplate、Mybatis、Jpa 的相关文章

随机推荐

  • ADB常用命令大全

    ADB环境变量配置 adb exe的路径 xff1a Android SDK platform tools 常用命令 adb help 查看帮助 adb version 查看adb版本号 adb devices 查看设备 adb conne
  • 【Java】最长公共子串

    Scanner in span class token operator 61 span span class token keyword new span span class token class name Scanner span
  • 【分布式】白话理解CAP与Kafka

    文章目录 一 CAP定理的引入二 CAP原理的解释1 CAP的定义2 AP的解释3 CP的解释4 AC的解释 三 CAP原理的总结四 类比kafka 官网AC 配置AP或者CP 一 CAP定理的引入 在过去 xff0c 因为信息处理的业务量
  • 手动搭建史上最高效最便宜的全自动图床Typora+PicGo+Gitee

    文章目录 效果图下载软件创建gitee存储配置picgogitee插件后重启picgo开机自启 xff0c 图片重命名查看当前图床的服务端口 xff0c 方便接下来的配置 测试上传 效果图 下载软件 Typora 43 PicGo 创建gi
  • 优秀的 Spring Boot 语言开源项目

    优秀的 Spring Boot 语言开源项目 xff0c 涵盖了企业级系统框架 文件文档系统 秒杀系统 微服务化系统 后台管理系统等各个方面 Spring Boot 中文索引 项目名称 分布式敏捷开发系统架构 项目简介 xff1a 基于 S
  • xxl-job中cron表达式详解

    7个部分组成 秒数 分钟 小时 日期 月份 星期 年份 可为空 5 每部分范围 及 符号解释 秒 0 59 分 0 59 小时 0 23 日期 1 31 L W C 月份 1 12 或者 JAN DEC 可以用0 11 或用字符串 JAN
  • 【高效能办公】快速搭建前端Mock数据接口供后端调用

    配置安装 span class token comment 全局安装 span span class token function npm span i 64 shymean mock server g span class token c
  • 【Linux】上传下载文件命令rz、sz

    文章目录 安装上传下载对比工具 安装 要使用rz sz命令传输文件需要给服务器安装lrzsz yum y install lrzsz 上传 上传文件只需在shell终端仿真器中输入命令 rz xff0c 即可从弹出的对话框中选择本地磁盘上的
  • 【Java】程序制作Docker镜像 推荐方案

    文章目录 背景制作条件Dockerfile指令 xff1a 实践步骤使用官网提供的基础镜像作为镜像基础设定容器的正确的时间和时区容器中采用非 root 用户权限启动应用程序 DockerFile样例COPY 与 ADD 区别 举个栗子 背景
  • 【Linux】ln -sf软连接

    文章目录 功能格式命令参数 xff1a 软链接硬链接 场景情况 功能 功能是为某一个文件在另外一个位置建立一个同步的链接 当 我们需要在不同的目录 xff0c 用到相同的文件时 xff0c 我们不需要在每一个需要的目录下都放一个必须相同的文
  • 【Java】Collection遍历使用Iterable迭代器

    span class token keyword package span span class token namespace com span class token punctuation span example span clas
  • 【SpringBoot】Thymeleaf融合ajax

    文章目录 效果ajax htmlController 效果 局部刷新 不会出现表单重复提交 ajax html span class token operator lt span span class token operator span
  • 【Java】file操作-删除文件中某一行中符合某一规则的

    效果 此处规则 xff0c 删除已空格分隔的域名行 xff0c 为防止因制表符等引起误删 xff0c 强制插入的规则空格分隔 同时要过滤掉 和其他非自己插入的数据格式 xff0c 避免误删 代码 package com ths arsena
  • 【Vue】组件ant design of vue

    文章目录 安装项目引入全局组件常见问题关键字避免处理校验异常es link栈溢出ant图库未加载 git追加到上一次提交文件 简单使用自定义组件 header列表加any问题ts类型 图标iocn 安装 span class token f
  • 【SpringBoot】配置文件application自定义内容引入

    背景 进行Spring Boot配置文件部署时 xff0c 发出警告Spring Boot Configuration Annotation Processor not configured xff0c 但是不影响运行 解决方案 pom x
  • ssh 登录失败

    SSH远程登录失败 xff0c 提示 Password authentication failed The authenticity of host 39 10 3 25 201 10 3 25 201 39 can 39 t be est
  • 【Vue】集成HTTP库Axios

    安装 进入vue项目目录 npm install axios 64 0 21 0 save 版本 简单使用 在一个页面中通过axios发送请求拿到后端数据 Home vue span class token function import
  • 【Nginx】mac快速安装使用

    效果图 安装 查找 brew search nginx 可用版本 使用 brew install nginx 安装nginx 查看brew列表 span class token punctuation span base span clas
  • 【Vue】vue3数据绑定

    文章目录 Vue2分析当前应用环境类型项目代码结构vue3取代生命周期函数的应用 vue3响应式ref xff08 xff09 数据绑定响应式reactive xff08 xff09 数据绑定比较两者 Vue2 分析当前应用环境 企业老项目
  • 【Java】SpringBoot整合多数据源JdbcTemplate、Mybatis、Jpa

    SpringBoot 整合 JdbcTemplate 多数据源 pom span class token comment lt 引入阿里的数据源 gt span span class token tag span class token t