您的位置:首页 > 编程语言 > Java开发

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);

}

}

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: