JPA多数据源配置

文章展示了如何在SpringBoot应用中配置多个数据源,并进行JPA相关设置,包括数据库连接信息、实体扫描、事务管理器的配置。同时提到了在`application.properties`中处理URL和jdbc-url的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

application.properites

spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/blue?serverTimezone=UTC

#spring.datasource.url = jdbc:mysql://localhost:3306/blue?serverTimezone=UTC

spring.datasource.username = root

spring.datasource.password = root

spring.datasource.driverClassName = com.mysql.jdbc.Driver

red.datasource.jdbc-url = jdbc:mysql://localhost:3306/red?serverTimezone=UTC

#red.datasource.url = jdbc:mysql://localhost:3306/red?serverTimezone=UTC

red.datasource.username = root

red.datasource.password = root

red.datasource.driverClassName = com.mysql.jdbc.Driver

#----------------------JPA------------------------------

# Specify the DBMS

spring.jpa.database = MYSQL

# Show or not log for each sql query

spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto = update

# Naming strategy

##spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultNamingStrategy

spring.jpa.generate-ddl=true

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

spring.datasource.jdbc-url, spring.datasource.url 以往使用url没有任何问题,通过配置引入后,提示需要jdbc-url,尝试后应用启动正常。入坑须清醒。

@ComponentScan(basePackages = { "controller", "service"/* ,"repository","pojo" */ })

//@EnableJpaRepositories(basePackages = "repository", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager")

@EnableJpaRepositories(basePackages = "repository", entityManagerFactoryRef = "entityManagerFactoryRed", transactionManagerRef = "transactionManagerRed")

@EntityScan("pojo")

@Configuration

@EnableTransactionManagement

public class MutiDataSourceCfg {

@Autowired

private Environment env;

@Bean

@ConfigurationProperties(prefix = "spring.datasource")

public DataSource dataSource() {

return DataSourceBuilder.create().build();

}

@Bean

public DataSource dataSourcex() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));

dataSource.setUrl(env.getProperty("spring.datasource.url"));

dataSource.setUsername(env.getProperty("spring.datasource.username"));

dataSource.setPassword(env.getProperty("spring.datasource.password"));

return dataSource;

}

@Bean

@ConfigurationProperties(prefix = "red.datasource")

public DataSource dataSourceRed() {

return DataSourceBuilder.create().build();

}

@Bean

public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

// builder.dataSource(getDataSource()).properties(null)

LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

DataSource ds=dataSource();

entityManagerFactoryBean.setDataSource(ds);

entityManagerFactoryBean.setPackagesToScan("pojo");

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);

entityManagerFactoryBean.setJpaProperties(getProperties());

return entityManagerFactoryBean;

}

public Properties getProperties() {

Properties properties = new Properties();

properties.setProperty("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));

properties.setProperty("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));

properties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));

properties.setProperty("spring.jpa.generate-ddl", env.getProperty("spring.jpa.generate-ddl"));

return properties;

}

@Bean

public TransactionManager transactionManager(

@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {

JpaTransactionManager transactionManager = new JpaTransactionManager();

transactionManager.setEntityManagerFactory(entityManagerFactory);

transactionManager.setDataSource(dataSource());

return transactionManager;

}

@Bean

public LocalContainerEntityManagerFactoryBean entityManagerFactoryRed() {

LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();

entityManagerFactoryBean.setDataSource(dataSourceRed());

entityManagerFactoryBean.setPackagesToScan("pojo");

JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);

entityManagerFactoryBean.setJpaProperties(getProperties());

return entityManagerFactoryBean;

}

@Bean

public TransactionManager transactionManagerRed(

@Qualifier("entityManagerFactoryRed") EntityManagerFactory entityManagerFactory) {

JpaTransactionManager transactionManager = new JpaTransactionManager();

transactionManager.setEntityManagerFactory(entityManagerFactory);

transactionManager.setDataSource(dataSourceRed());

return transactionManager;

}

}

Spring Boot结合JPA (Java Persistence API) 配置多数据源通常是为了处理数据库分层架构,例如有生产环境、测试环境和开发环境等。以下是基本的配置步骤: 1. 添加依赖:首先,在`pom.xml`或`build.gradle`文件中添加Spring Data JPA和对应的数据源管理库(如HikariCP、Druid等)。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'com.alibaba.druid:druid-spring-boot-starter' ``` 2. 定义数据源:创建一个或多份`DataSource` bean,每个bean代表一个数据源,通常在application.yml或application.properties中配置。 ```yaml # application.yml 或 application.properties spring.datasource.master.url=jdbc:mysql://localhost/masterdb spring.datasource.master.username=root spring.datasource.master.password=masterpass spring.datasource.secondary.url=jdbc:mysql://localhost/secondarydb spring.datasource.secondary.username=root spring.datasource.secondary.password=secpass ``` 3. 使用@Profile注解区分数据源:通过Spring Profile来控制在运行时切换数据源。例如: ```java @Configuration @EnableJpaRepositories(basePackages = "com.example.demo.repository") public class JpaConfig { @Autowired private Environment env; @Profile("prod") @Bean(name = "primaryDataSource") public DataSource primaryDataSource() { // 生产环境数据源配置 } @Profile("test") @Bean(name = "secondaryDataSource") public DataSource secondaryDataSource() { // 测试环境数据源配置 } @Profile({"dev", "default"}) @Bean(name = "dataSource") public DataSource dataSource() { // 开发环境默认数据源配置 } } ``` 4. 使用Repository:在Repository接口上加入`@Transactional`注解,并指定事务所使用的数据源。如果未指定,默认会使用`dataSource`。 ```java @Repository @Transactional(rollbackFor = Exception.class) public interface MyRepository extends JpaRepository<MyEntity, Long> { //... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值