SpringBoot多数据源配置
在用springboot开发项目时,随着业务量的扩大,我们通常会进行数据库拆分或是引入其他数据库,从而我们需要配置多个数据源,下面基于Spring-data-jpa配置多数据源,希望对大家有所帮助
项目目录结构
1.png
1、先在application.yml 中配置多个数据库
spring:
datasource:
database1:
url: jdbc:mysql://localhost:3306/database1?useUnicode=true&characterEncoding=utf8
username: root
password: 12345678
driverClassName: com.mysql.jdbc.Driver
database2:
url: jdbc:mysql://localhost:3306/database2?useUnicode=true&characterEncoding=utf8
username: root
password: 12345678
driverClassName: com.mysql.jdbc.Driver
# type: com.alibaba.druid.pool.DruidDataSource
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
database-platform: org.hibernate.dialect.MySQL5Dialect
这里配置了database1、database2两个数据库
2、配置数据库连接属性
在DataBase1Properties类中配置database1数据库连接的属性
@ConfigurationProperties(prefix = "spring.datasource.database1")
@Component
@Data
public class DataBase1Properties {
private String url;
private String username;
private String password;
private String driverClassName;
}
在DataBase2Properties类中配置database2数据库连接的属性
@ConfigurationProperties(prefix = "spring.datasource.database2")
@Component
@Data
public class DataBase2Properties {
private String url;
private String username;
private String password;
private String driverClassName;
}
3、数据库字段设置
在DataSourceConfig类中设置两个数据库的连接数据,在本文章中使用的是springboot2.0默认的Hikari连接,如果使用的是alibaba的druid,把HikariDataSource替换成DruidDataSource即可
@Configuration
@Slf4j
public class DataSourceConfig {
@Autowired
private DataBase1Properties dataBase1Properties;
@Autowired
private DataBase2Properties dataBase2Properties;
@Bean(name = "dataBase1DataSource")
@Primary
public DataSource dataBase1DataSource(){
log.info("dataBase1DataSource初始化----111111");
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(dataBase1Properties.getUrl());
dataSource.setUsername(dataBase1Properties.getUsername());
dataSource.setPassword(dataBase1Properties.getPassword());
dataSource.setDriverClassName(dataBase1Properties.getDriverClassName());
return dataSource;
}
@Bean(name = "dataBase2DataSource")
public DataSource dataBase2DataSource(){
log.info("dataBase2DataSource初始化----222222");
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(dataBase2Properties.getUrl());
dataSource.setUsername(dataBase2Properties.getUsername());
dataSource.setPassword(dataBase2Properties.getPassword());
dataSource.setDriverClassName(dataBase2Properties.getDriverClassName());
return dataSource;
}
}
4、配置数据源、连接工厂、事物管理器、dao目录
在DataBaseConfig1类中
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryDataBase1", // 配置连接工厂
transactionManagerRef = "transactionManagerDatabase1", // 配置事物管理器
basePackages = {"com.lss.dao.database1"} // 设置dao所在位置
)
public class DataBase1Config {
// 配置数据源
@Autowired
private DataSource dataBase1DataSource;
@Primary
@Bean(name = "entityManagerFactoryDataBase1")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase1(EntityManagerFactoryBuilder builder) {
return builder
// 设置数据源
.dataSource(dataBase1DataSource)
//设置实体类所在位置.扫描所有带有 @Entity 注解的类
.packages("com.lss.entity.database1")
// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
.persistenceUnit("database1PersistenceUnit")
.build();
}
/**
* 配置事物管理器
*
* @param builder
* @return
*/
@Bean(name = "transactionManagerDatabase1")
PlatformTransactionManager transactionManagerDatabase1(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryDataBase1(builder).getObject());
}
}
在DataBaseConfig2类中
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryDataBase2", // 配置连接工厂
transactionManagerRef = "transactionManagerDatabase2", // 配置事物管理器
basePackages = {"com.lss.dao.database2"} // 设置dao所在位置
)
public class DataBase2Config {
// 配置数据源
@Autowired
@Qualifier("dataBase2DataSource")
private DataSource dataBase2DataSource;
@Bean(name = "entityManagerFactoryDataBase2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase2(EntityManagerFactoryBuilder builder) {
return builder
// 设置数据源
.dataSource(dataBase2DataSource)
//设置实体类所在位置.扫描所有带有 @Entity 注解的类
.packages("com.lss.entity.database2")
// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
.persistenceUnit("database2PersistenceUnit")
.build();
}
/**
* 配置事物管理器
*
* @param builder
* @return
*/
@Bean(name = "transactionManagerDatabase2")
PlatformTransactionManager transactionManagerDatabase2(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryDataBase2(builder).getObject());
}
}
@Primary的意思是在众多相同的bean中,优先使用用@Primary注解的bean.而@Qualifier这个注解则指定某个bean有没有资格进行注入。
此时,多数据源的主要配置已经完成,下面是一些实体类、dao的常用配置
5、配置实体类,dao
在User、Student、UserDaoRepository、StudentDaoRepository四个类中分别配置如下
2.png
上面是最简单的类,就不贴代码了
6、数据库配置
分别创建两个数据库database1、database2,database1中创建tbl_user表,database2中创建tbl_student表,如下图
3.png
7、接口实现
在TestController.java中添加接口访问
@RestController
public class TestController {
@Autowired
private UserDaoRepository userDaoRepository;
@Autowired
private StudentDaoRepository studentDaoRepository;
@GetMapping(value = "/getuser")
public List<User> getuser(){
List<User> all = userDaoRepository.findAll();
return all;
}
@GetMapping(value = "/getstudent")
public List<Student> getstudent(){
List<Student> all = studentDaoRepository.findAll();
return all;
}
}
至此,所有的类都已经实现,启动项目
访问接口,数据如下
4.png
来源:CSDN
作者:Wuli波板糖
链接:https://blog.csdn.net/P397226804/article/details/103744095