SpringBoot整合MyBatis,Druid配置多数据源

前言

因为项目要求需要两个项目中同时使用3个数据源,然后就折腾了一下。从网上也看了许多的案例,但是都多多少少有问题。比如说MyBatis只能用注解开发,而不能用配置之类的。这个我觉得无坑版吧,尽量会说的详细一点。

目录结构

structure

主要依赖
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--    druid 连接池  -->        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

<!--  分页插件,尝试高版本和spring-boot-starter-pagehalper 均启动失败     -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

在 pom.xml的<build>标签中添加静态资源扫描:

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

配置文件

application.yml 配置

主要给出数据源的配置


spring: 
  datasource:
    pigxpf:
      type: com.alibaba.druid.pool.DruidDataSource
      
      # 注意在配置多数据源时这里要用 jdbc-url,驱动名需要用 driver-class-name
      jdbc-url: jdbc:mysql://localhost:3306/pf?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

    pigxhr:
      type: com.alibaba.druid.pool.DruidDataSource
      jdbc-url: jdbc:mysql://localhost:3306/hr?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis配置都在 resources/mybatis/mabatis-config.xml中,这里配置并不会自动扫描。
mybatis:
  # 加载全局的配置文件
  configLocation: classpath:mybatis/mybatis-config.xml
mybatis-config配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 开启驼峰匹配 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="useColumnLabel" value="true" />
        <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
            Derby)。 系统默认值是false,设置只是为了展示出来 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>

    <!-- 分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 数据库方言 -->
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <!-- 设置为true时,使用RowBounds分页会进行count查询 会去查询出总数 -->
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>
Application.java启动类

我这里什么都没动也能正常用,有的博客说要取消自动扫描,因为自动扫描只会加载一个数据源。

配置类

DataSourceConfig.java
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.context.annotation.Primary;

import javax.sql.DataSource;


/**
 * @author: litblue
 * @Time : 2019/7/28 10:38
 * @Email: litblue@163.com
 * 绝不敷衍,毫不懈怠
 *
 * 手动配置数据源
 *
 */

@Configuration
public class DataSourceConfig {

    @Bean(name = "pigxpfDatasource")
    @Primary   /*  主要数据源 */
    @ConfigurationProperties(prefix = "spring.datasource.pigxpf")
    public DataSource pigxpfDatasource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "pigxhrDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.pigxhr")
    public DataSource pighrDatasource(){
        return DataSourceBuilder.create().build();
    }
}

MyBatisPigxpfConfig.java

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;


/**
 * @author: litblue
 * @Time : 2019/7/28 10:53
 * @Email: litblue@163.com
 * 绝不敷衍,毫不懈怠
 */

@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxpfConfig {

    @Autowired
    @Qualifier("pigxpfDatasource")
    private DataSource pigxpfSource;

    // 加载配置文件
    @Value("${mybatis.configLocation}")
    private String configLocation;


    @Bean(name="pigxpfSqlFactory")
    @Primary
    public SqlSessionFactory pigxpfSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(pigxpfSource);
        // 配置类型别名
        factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
        // 配置mapper的扫描,找到所有的mapper.xml映射文件
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);

        // 加载配置文件
        factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));

        return factoryBean.getObject();
    }

    @Bean(name="pigxpfSqlFactory")
    @Primary
    public SqlSessionTemplate pigxpfSqlSessionTemplate() throws Exception{
        SqlSessionTemplate template = new SqlSessionTemplate(pigxpfSqlSessionFactory());
        return template;
    }
}

MyBatisPigxhrConfig.java

这里与上述相同,只是不需要添加@Primary 注解了。

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author: litblue
 * @Time : 2019/7/28 11:26
 * @Email: litblue@163.com
 * 绝不敷衍,毫不懈怠
 */

@Configuration
@MapperScan(basePackages = {"com.pigx.pigxpf.mapper"},sqlSessionFactoryRef = "pigxpfSqlFactory")
public class MyBatisPigxhrConfig {

    @Autowired
    @Qualifier("pigxhrDatasource")
    private DataSource pigxhrSource;

    @Value("${mybatis.configLocation}")
    private String configLocation;

    @Bean(name="pigxhrSqlFactory")
    public SqlSessionFactory pigxhrSqlSessionFactory() throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(pigxhrSource);
        // 配置类型别名
        factoryBean.setTypeAliasesPackage("com.pigx.pigxpf.entity");
        // 配置mapper的扫描,找到所有的mapper.xml映射文件
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml");
        factoryBean.setMapperLocations(resources);

        // 加载配置文件
        factoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));

        return factoryBean.getObject();
    }

    @Bean(name="pigxhrSqlFactory")
    public SqlSessionTemplate pigxhrSqlSessionTemplate() throws Exception{
        SqlSessionTemplate template = new SqlSessionTemplate(pigxhrSqlSessionFactory());
        return template;
    }
}
运行结果

result

最后

关于Druid 的监控的暂时还没有配置,也还不知道咋弄,过段时间再更新。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot是一个快速开发框架,而MyBatis是一个流行的ORM框架,Druid是一个高性能的数据库连接池。将它们整合在一起可以提高开发效率和系统性能。具体步骤如下: 1. 引入相关依赖:在pom.xml文件中添加spring-boot-starter-jdbc、mybatis-spring-boot-starter和druid-spring-boot-starter依赖。 2. 配置数据源:在application.properties文件中配置数据源信息,包括数据库URL、用户名、密码等。 3. 配置MyBatis:在application.properties文件中配置MyBatis相关信息,包括mapper文件路径、实体类包路径等。 4. 配置Druid:在application.properties文件中配置Druid相关信息,包括连接池大小、监控页面路径等。 5. 编写Mapper接口和SQL语句:在Mapper接口中定义SQL语句,并使用@Mapper注解标注该接口。 6. 编写Service层和Controller层:在Service层中调用Mapper接口,实现业务逻辑;在Controller层中处理请求和响应。 7. 启动应用程序:使用Spring Boot的启动器启动应用程序,访问相关接口即可。 总之,整合Spring BootMyBatisDruid可以让我们更方便地开发数据库应用程序,提高开发效率和系统性能。 ### 回答2: Spring Boot 是目前非常热门的一种快速构建 web 应用程序的框架,而 Mybatis 是一款非常流行的 Java 数据库持久化框架,Druid 是阿里巴巴开发的数据库连接池和监控工具。Spring Boot 整合 MybatisDruid 的开发方式比较简单,只需要进行相应的配置即可。 首先,在 pom.xml 文件中添加 MybatisDruid 的依赖: ``` <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> ``` 然后,在 application.yml 或 application.properties 中添加相应的配置,以下是一个示例: ``` spring: datasource: type: com.alibaba.druid.pool.DruidDataSource username: root password: root url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.jdbc.Driver druid: min-idle: 5 max-active: 20 initial-size: 5 test-on-borrow: true validation-query: SELECT 1 mybatis: mapper-locations: classpath:mapper/*.xml ``` 其中,spring.datasource 下的配置数据库连接相关的配置druid 下的配置是连接池相关的配置mybatis 下的配置Mybatis 相关的配置。 最后,在需要使用 Mybatis 的类上添加 @Mapper 注解即可,例如: ``` @Mapper public interface UserDao { List<User> selectAll(); void insert(User user); } ``` 这样,我们就通过 Spring Boot 整合MybatisDruid,并且可以方便地使用它们来访问数据库。同时,Druid 还提供了一些监控和统计功能,可以方便地了解应用程序访问数据库的性能和健康情况。 ### 回答3: 随着互联网应用越来越普及,Java Web开发也变得越来越火热,相应的Spring BootMyBatisDruid等技术也得到了广泛的应用。其中,Spring Boot是基于Spring Framework的一种全新框架,通过封装成熟的框架和工具,提高了开发效率,减少了配置量;MyBatis是一款优秀的基于Java的ORM框架,可以让开发人员更加专注于SQL本身,而无需过多关注底层的操作。Druid是一个强大的数据库连接池,具有监控、性能分析、SQL注入检查和防御、不同操作系统适配等特点,能够有效提高应用的性能和稳定性。 Spring Boot整合MyBatisDruid,可以将这三个技术更有效地结合起来,发挥它们的优点。 具体步骤如下: 1. 创建基于Spring Boot的Web工程,并在pom.xml文件中引入相关依赖。 ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.22</version> </dependency> ``` 2. 创建数据库连接配置文件application.properties。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.config-location=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:com/example/mapper/*Mapper.xml mybatis.type-aliases-package=com.example.entity # Druid数据源配置 # 初始化大小、最小、最大连接数 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 # 配置连接空闲的最大时间,超时将被关闭,单位毫秒 spring.datasource.maxEvictableIdleTimeMillis=900000 # 配置连接池中的连接创建时的默认自动提交配置 spring.datasource.defaultAutoCommit=true # 对于长时间不使用的连接强制关闭 spring.datasource.removeAbandoned=true spring.datasource.removeAbandonedTimeout=1800 spring.datasource.logAbandoned=true spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.filters=stat,wall,log4j ``` 3. 创建MyBatis配置文件mybatis-config.xml。 ```xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true" /> <setting name="logImpl" value="LOG4J" /> </settings> </configuration> ``` 4. 在Spring Boot的启动类上添加@Configuration注解,并通过@Bean注解来配置SqlSessionFactory和SqlSessionTemplate。 ```java @SpringBootApplication @Configuration @MapperScan(basePackages = "com.example.mapper") public class Application { @Autowired DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate() throws Exception { SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory()); return sqlSessionTemplate; } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 创建Mapper接口和对应的XML文件。 ```java public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User selectUserById(int id); } ``` ```xml <mapper namespace="com.example.mapper.UserMapper"> <resultMap id="userMap" type="com.example.entity.User"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="password" property="password" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="VARCHAR"/> </resultMap> <select id="selectUserById" resultMap="userMap"> SELECT id, username, password, age FROM user WHERE id = #{id} </select> </mapper> ``` 6. 创建实体类,并注入Mapper接口到Service中进行操作。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User selectById(int id) { return userMapper.selectUserById(id); } } ``` 7. 创建Controller,提供对外RESTful API接口。 ```java @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User selectById(@PathVariable int id) { return userService.selectById(id); } } ``` 综上,以上是Spring Boot整合MyBatisDruid的流程。由于Spring Boot的封装,开发人员只需要关注业务逻辑的处理,而无需过多关注底层技术的实现细节,大大提高了开发效率。同时,MyBatisDruid提供了非常强大和灵活的数据操作支持和连接池管理,可以有效地提高应用的性能和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值