Springboot使用JPA配置多数据源
https://zhuanlan.zhihu.com/p/299055754
本人在最近的项目中,需要使用JPA配置两个数据源来完成一些功能,以此记录配置过程。方便以后使用:
第一步:配置文件中加入相应的配置。
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.database=mysql
#预发环境数据库
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/toutiao?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
#预发环境数据库
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/driver_manager?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
第二步:加入对应的配置类。
1、DataSourceConfig类,配置两个数据源。
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDbDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDbDataSource() {
return DataSourceBuilder.create().build();
}
}
2、主数据源配置类,PrimaryConfig类。
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.kunkun.jpa.primary"} //需要修改的地方
)
public class PrimaryConfig {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties())
.packages("com.kunkun.jpa.model.primary") //设置实体类所在位置与副数据源区分,需要修改
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map getVendorProperties() {
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.ddl-auto",
"create");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
return properties;
}
@Autowired
private Environment env;
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
2、主数据源配置类,PrimaryConfig类。
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.kunkun.jpa.primary"} //需要修改的地方
)
public class PrimaryConfig {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties())
.packages("com.kunkun.jpa.model.primary") //设置实体类所在位置与副数据源区分,需要修改
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map getVendorProperties() {
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.ddl-auto",
"create");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
return properties;
}
@Autowired
private Environment env;
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
3、SecondaryConfig,辅数据源配置
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.kunkun.jpa.secondary"}) //设置DAO接口层所在包位置与主数据源区分
public class SecondaryConfig {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties())
.packages("com.kunkun.jpa.model.secondary") //设置实体类所在包的位置与主数据源区分
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map getVendorProperties() {
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.ddl-auto",
env.getProperty("update"));
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
return properties;
}
@Autowired
private Environment env;
@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
第三步:设置实体类所在位置
实体类:
@Entity
@Data
@Table(name = "user")
public class User {
@Id
private Integer id;
/**
* 名字
*/
private String name;
/**
* 密码
*/
private String password;
}
DAO类:
public interface UserDao extends JpaRepository<User, Integer>,
JpaSpecificationExecutor<User> {
/**
* 根据title查数据
*
* @param id
* @return
*/
@Transactional
@Query("SELECT dr.name from User dr where dr.id = :id")
String findDataByTitle(@Param("id") Integer id);
}
上面标红的地方是需要修改的地方,对于配置文件和数据源配置类的部分是可以修改的。建议名字不修改,直接复制就好了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2020-01-12 js判断是否是ie浏览器且给出ie版本
2020-01-12 js判断文件大小利用img 的 dynsrc,兼容IE10 及以上
2020-01-12 java 个人主页
2020-01-12 Java的——String类、StringBuffer和StringBuilder、不可变和可变字符序列使用陷阱
2020-01-12 windows.onload和body的onload属性的区别
2020-01-12 jquery中class选择器的用法,选择两个class
2020-01-12 #JS# 如何判断一个字符串是否为日期格式