就是让一个项目应用并使用多个数据库,这里采用的是SpringBoot2.0、MySql5.7,使用两个两个MySql数据库
1、建立两个数据库
2、建立一个SpringBoot项目
3、Pom文件
<?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>
<groupId>czs</groupId>
<artifactId>springboot-manyDatasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-manyDatasource</name>
<description>springboot使用多个数据源(多个数据库)</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<!-- 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.0</version><!-- 1.3.0以上的版本没有@MapperScan以及@Select注解 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4、书写application.properties文件,配置两个数据库连接
###datasource1
spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test1.jdbc-url = jdbc:mysql://192.168.25.11:3306/18-08-12-manyDatasource1?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
spring.datasource.test1.password =
###datasource2
spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.test2.jdbc-url = jdbc:mysql://192.168.25.11:3306/18-08-12-manyDatasource2?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
spring.datasource.test2.password =
发现前缀的不同没有?
数据源一是:spring.datasource.test1. 数据源二是:spring.datasource.test2.
这里记着配置文件中配置数据源是有前缀的,第七步记得有这个前缀
5、书写对应数据库的实体类文件-------此处应用了lombok注解,不懂自行百度学习....
package czs.entity;
import lombok.Data;
/**
* @author czs
* @version 创建时间:2018年8月12日 下午2:30:46
*/
@Data
public class User {
private String name;
private long age;
}
6、书写第一个Dao层的Mapper文件以及Service层
Mapper
package czs.mapper1;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import czs.entity.User;
public interface UserMapper1 {
// 查询语句
@Select("SELECT * FROM users WHERE NAME = #{name}")
User findByName(@Param("name") String name);
// 添加
@Insert("INSERT INTO users(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
Service
package czs.mapper1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author czs
* @version 创建时间:2018年8月12日 下午7:28:07
*/
@Service
public class ManyService1 {
@Autowired
private UserMapper1 userMapper1;
public int insert(String name, Integer age) {
return userMapper1.insert(name, age);
}
}
6、书写第二个Dao层的Mapper文件--------------其实和上面那个想相比就是包名和类名以及Service层中的Mapper引用不同
Mapper
package czs.mapper2;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import czs.entity.User;
public interface UserMapper2 {
// 查询语句
@Select("SELECT * FROM users WHERE NAME = #{name}")
User findByName(@Param("name") String name);
// 添加
@Insert("INSERT INTO users(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
Service
package czs.mapper2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author czs
* @version 创建时间:2018年8月12日 下午7:28:07
*/
@Service
public class ManyService2 {
@Autowired
private UserMapper2 userMapper2;
public int insert(String name, Integer age) {
return userMapper2.insert(name, age);
}
}
7、配置数据源、事务管理器。。。非常重要的一步,也是这个来分配数据源给哪些类包的
注意类中@MapperScan注解中的basePackages的内容!
第4步说过注意前缀,就是在下面的@ConfigurationProperties(prefix = "spring.datasource.test1")中,是根据这个来选择数据源的
package czs.datasource;
import javax.sql.DataSource;
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.jdbc.datasource.DataSourceTransactionManager;
/**
* 读取DataSource01数据源<br>
*/
// DataSource01
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "czs.mapper1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {
/**
* @methodDesc: 功能描述:(配置test01数据库)
*/
@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
/**
* @methodDesc: 功能描述:(test1 sql会话工厂)
*/
@Bean(name = "test1SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// bean.setMapperLocations(
// new
// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
}
/**
* @methodDesc: 功能描述:(test1 事物管理)
*/
@Bean(name = "test1TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test1SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
8、还是非常重要的一步,也是这个来分配数据源给哪些类包的
就是复制上面那步的类,将@MapperScan注解中的basePackages改为放另一个Mapper接口的包名就好!
以下是两个类中不同的部分。。。。。。。。。。。
@MapperScan(basePackages = "czs.mapper1", sqlSessionFactoryRef = "test1SqlSessionFactory")
@ConfigurationProperties(prefix = "spring.datasource.test1")
@MapperScan(basePackages = "czs.mapper2", sqlSessionFactoryRef = "test1SqlSessionFactory")
@ConfigurationProperties(prefix = "spring.datasource.test2")
9、Controller层
package czs;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import czs.mapper1.ManyService1;
import czs.mapper2.ManyService2;
/**
* @author czs
* @version 创建时间:2018年8月12日 下午9:03:02
*/
@RestController
public class ManyController {
@Autowired
private ManyService1 manyService1;
@Resource
private ManyService2 manyService2;
@RequestMapping(value = "datasource1")
public int datasource1(String name, Integer age) {
return manyService1.insert(name, age);
}
@RequestMapping(value = "datasource2")
public int datasource2(String name, Integer age) {
return manyService2.insert(name, age);
}
}
1 注意要注入两个Service
2 注意有两个@RequestMapping,里面的映射路径不一样
10、尝试访问
11、查看数据库
数据源一插入成功!
数据源二插入成功!
最后,多数据源的事务可以参考我的下一篇文章:SpringBoot多数据源事务管理机制