Spring Boot配置多数据源(MyBatis + MySQL)
主要介绍 springboot+mybatis 使用多数据源
- 新建一个SpringBoot项目,导入依赖
<dependencies>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
</dependencies>
- 编写配置文件
server:
port: 8888 # 启动端口
spring:
datasource:
db1: # 数据源1
jdbc-url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: cvzhanshi
driver-class-name: com.mysql.cj.jdbc.Driver
db2: # 数据源2
jdbc-url: jdbc:mysql://localhost:3306/springsecurity?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
username: root
password: cvzhanshi
driver-class-name: com.mysql.cj.jdbc.Driver
注意事项
各个版本的 springboot 配置 datasource 时参数有所变化,例如低版本配置数据库 url 时使用 url 属性,高版本使用 jdbc-url 属性,请注意区分。
- 编写连接数据源的配置类
第一个数据源的配置文件
/**
* @author cVzhanshi
* @create 2021-08-10 16:14
*/
@Configuration
@MapperScan(basePackages = "cn.cvzhanshi.testdatasources.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {
//经过测试,@Primary注解去掉也不影响多数据源的使用
//@Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
@Bean("db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1") //读取application.yml中的配置参数映射成为一个对象
public DataSource getDb1DataSource(){
return DataSourceBuilder.create().build();
}
//@Primary
@Bean("db1SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db1/*.xml"));
return bean.getObject();
}
//@Primary
@Bean("db1SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
第二个数据源的配置文件
/**
* @author cVzhanshi
* @create 2021-08-10 16:16
*/
@Configuration
@MapperScan(basePackages = "cn.cvzhanshi.testdatasources.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DataSourceConfig2 {
@Bean("db2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDb1DataSource(){
return DataSourceBuilder.create().build();
}
@Bean("db2SqlSessionFactory")
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));
return bean.getObject();
}
@Bean("db2SqlSessionTemplate")
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
- 编写对应数据的User实体类
/**
* @author cVzhanshi
* @create 2021-08-10 16:21
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer Id;
private String username;
private String password;
}
- 编写mapper层,其中不同数据源要分包编写,与配置类扫描的对应
cn.cvzhanshi.testdatasources.mapper.db1.UserMapper
/**
* @author cVzhanshi
* @create 2021-08-10 16:18
*/
public interface UserMapper {
List<User> getAllUser();
}
cn.cvzhanshi.testdatasources.mapper.db2.UserMapper2
/**
* @author cVzhanshi
* @create 2021-08-10 16:18
*/
public interface UserMapper2 {
List<User> getAllUser();
}
- 编写与之对应的映射文件,映射文件也要分包编写,与配置类配置的路径对应
mapper/db1/UserMapper.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="cn.cvzhanshi.testdatasources.mapper.db1.UserMapper" >
<select id="getAllUser" resultType="cn.cvzhanshi.testdatasources.entity.User">
select id,username,password from user;
</select>
</mapper>
mapper/db2/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="cn.cvzhanshi.testdatasources.mapper.db2.UserMapper2" >
<select id="getAllUser" resultType="cn.cvzhanshi.testdatasources.entity.User">
select id,username,password from users;
</select>
</mapper>
- 编写service层,业务层
/**
* @author cVzhanshi
* @create 2021-08-10 16:27
*/
@Service
public class UserService {
@Autowired
private UserMapper userMapperDb1;
@Autowired
private UserMapper2 userMapperDb2;
public List<User> getAllUserForDb1(){
List<User> allUser = userMapperDb1.getAllUser();
return allUser;
}
public List<User> getAllUserForDb2(){
List<User> allUser = userMapperDb2.getAllUser();
return allUser;
}
}
- 编写controller层
/**
* @author cVzhanshi
* @create 2021-08-10 16:29
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/db1")
public List<User> getAllUserForDb1(){
List<User> allUserForDb1 = userService.getAllUserForDb1();
return allUserForDb1;
}
@GetMapping("/db2")
public List<User> getAllUserForDb2(){
List<User> allUserForDb2 = userService.getAllUserForDb2();
return allUserForDb2;
}
}
- 测试
最后,项目结构
注意事项
- 在 service 层中根据不同的业务注入不同的 dao 层
- 如果是主从复制- -读写分离:比如 db1 中负责增删改,db2 中负责查询。但是需要注意的是负责增删改的数据库必须是主库(master)
Spring Boot配置多数据源(MyBatis-Plus + Oracle)
由于比较类似,这里只说出不同和注意点
- 导入相关依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.4.1</version>
</dependency>
<!-- oracle驱动依赖 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
- 在编写配置类的时候注意点
- 如果不想使用默认的数据源,如druid,需要注意的
- 其他注意点,是在在编写配置文件的时候要注意使用url或者二jdbc-url,这样会影响druid是否导入成功,要检查一下数据源是否为druid
- 其他的注意事项就是在写mapper的时候要按照规范来创建