SpringBoot 2.0整合mybatis 实现多数据源
2019-03-29 10:07
741 查看
闲来无事,偶然看见了springboot 可以整合多个数据源,本文就来实现一下! 参考例子
本文使用的是springboot 2.1.3,mysql6.0以上的版本,具体配置较之前的版本可能有点差距,详细配置请看代码。
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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>multi-data-source</artifactId> <version>0.0.1-SNAPSHOT</version> <name>multi-data-source</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.13</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.properties :
first.datasource.jdbc-url=jdbc:mysql://localhost:3306/first?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false first.datasource.username=root first.datasource.password=123456 first.datasource.driver-class-name=com.mysql.cj.jdbc.Driver first.datasource.type=com.alibaba.druid.pool.DruidDataSource second.datasource.jdbc-url=jdbc:mysql://localhost:3306/second?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false second.datasource.username=root second.datasource.password=123456 second.datasource.driver-class-name=com.mysql.cj.jdbc.Driver second.datasource.type=com.alibaba.druid.pool.DruidDataSource server.port=8090
这里的配置前缀可自行定义,springboot2.0以上的版本,数据库的 url 变成了 jdbc-url,mysql 6.0 驱动 从 com.mysql.jdbc.Driver 变成了 com.mysql.cj.jdbc.Driver 请注意版本问题,不然会报错
项目结构:
代码:
两个配置类,StudentMybatisConfig 、 UserMybatisConfig
package com.example.multidatasource.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.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.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; import java.io.IOException; /** * @author HX * @date 2019-03-28 15:24 */ @Configuration @MapperScan(basePackages = "com.example.multidatasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate") public class UserMybatisConfig { @Bean(name = "userDataSource") @Primary // 表示这个数据源是默认数据源,第二个数据源配置类不用加 @ConfigurationProperties(prefix = "first.datasource") public DataSource userDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws IOException { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // 添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources("classpath*:mapper/user/*.xml")); try { return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } }
package com.example.multidatasource.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.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.context.annotation.Primary; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; import java.io.IOException; /** * @author HX * @date 2019-03-28 15:52 */ @Con 1cca8 figuration @MapperScan(basePackages = "com.example.multidatasource.mapper.stu", sqlSessionTemplateRef = "stuSqlSessionTemplate") public class StudentMybatisConfig { @Bean @ConfigurationProperties(prefix = "second.datasource") // 数据源配置前缀 public DataSource stuDataSource() { return DataSourceBuilder.create().build(); } @Bean public SqlSessionFactory stuSqlSessionFactory(@Qualifier("stuDataSource") DataSource dataSource) throws IOException { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // 添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources("classpath*:mapper/stu/*.xml")); try { return bean.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate stuSqlSessionTemplate(@Qualifier("stuSqlSessionFactory") SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } }
mapper 注意包结构
package com.example.multidatasource.mapper.stu; import com.example.multidatasource.domain.Student; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /** * @author HX * @date 2019-03-28 16:19 */ @Mapper @Repository public interface StudentMapper { Student findStudentByName(String name); }
package com.example.multidatasource.mapper.user; import com.example.multidatasource.domain.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; /** * @author HX * @date 2019-03-28 16:12 */ @Mapper @Repository public interface UserMapper { User findUserById(String id); }
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.example.multidatasource.mapper.stu.StudentMapper"> <select id="findStudentByName" resultType="com.example.multidatasource.domain.Student" parameterType="java.lang.String"> SELECT name ,age FROM t_student where id = #{id}; </select> </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.example.multidatasource.mapper.user.UserMapper"> <select id="findUserById" resultType="com.example.multidatasource.domain.User" parameterType="java.lang.String"> SELECT username userName,password passWord FROM t_user where id = #{id}; </select> </mapper>
数据库数据:
测试:
package com.example.multidatasource; import com.example.multidatasource.domain.Student; import com.example.multidatasource.domain.User; import com.example.multidatasource.mapper.stu.StudentMapper; import com.example.multidatasource.mapper.user.UserMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MultiDataSourceApplicationTests { @Autowired UserMapper userMapper; @Autowired StudentMapper stuMapper; @Test public void contextLoads() { User user = userMapper.findUserById("1"); Student student = stuMapper.findStudentByName("1"); System.out.println(user); System.out.println(student); } }
结果:
相关文章推荐
- Spring Boot 整合 Mybatis 实现 Druid 多数据源
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- Springboot整合Mybatis实现Druid多数据源
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- Spring Boot 整合mybatis 使用多数据源的实现方法
- SpringBoot + Mybatis plus 实现多数据源整合
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
- (十一)Spring Boot整合Mybatis使用druid实现多数据源自动切换
- springboot 2.0 整合mybatis 多数据源(完整版)
- 从零实现 Spring Boot 2.0 整合 weixin-java-mp(weixin-java-tools) 获取 openId,用于微信授权
- Springboot2.0整合elasticsearch实现CRUD操作
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例(转)
- springBoot(13)---整合Druid实现多数据源和可视化监控
- Spring boot整合mybatis实现数据的CRUD
- Spring boot +Mybatis 实现多数据源(一:最简单版本)
- Spring Boot2.0 整合mybatis、分页插件、druid