如何在Spring Boot项目中配置双数据源(即两个不同的数据库)时,设置自增ID生成器(identifierGenerator)?
时间: 2024-10-23 10:14:32 浏览: 15
在Spring Boot项目中配置双数据源并为每个数据源设置自增ID生成器,通常需要以下几个步骤:
1. **添加依赖**:
首先,在`pom.xml`文件中添加Spring JPA和HikariCP的依赖,如果还没有的话,因为它们都是数据源管理所必需的。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
```
2. **创建数据源配置**:
在`application.properties`或`application.yml`中添加两个数据源,分别配置数据库URL、用户名、密码等信息。例如:
```properties
spring.datasource.master.url=jdbc:mysql://localhost/master_db
spring.datasource.master.username=root
spring.datasource.master.password=master_password
spring.datasource.secondary.url=jdbc:mysql://localhost/secondary_db
spring.datasource.secondary.username=root
spring.datasource.secondary.password=secondary_password
```
3. **启用JPA和事务管理**:
确保你在`application.properties`或`application.yml`中启用了Spring Data JPA和事务管理,如:
```yaml
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=true
```
4. **实体类和注解**:
对于每个数据源对应的实体类(通常是Pojo类),需要设置`@Table`注解,并指定数据源(可以使用`@Table(name = ..., schema = "db_name")`)。比如:
```java
@Entity
@Table(name = "users", schema = "secondary_db")
public class SecondaryUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other fields...
}
```
5. **使用DataSourceTransactionManager**:
如果你想在不同的数据源上运行事务,需要使用`DataSourceTransactionManager`。在Spring Boot中,这通常是自动配置的,但你可以确认它是否已经存在,如果没有则添加:
```java
@Configuration
@EnableTransactionManagement
public class TransactionConfig {
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public HibernateEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource) {
HibernateEntityManagerFactoryBean factoryBean = new HibernateEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPackagesToScan("your.package.name"); // your entities
return factoryBean;
}
}
```
6. **访问数据源**:
使用`@Transactional`注解控制在哪个数据源上下文执行操作,例如:
```java
@Service
public class UserService {
@Autowired
@Qualifier("secondaryDataSource")
private LocalContainerEntityManagerFactoryBean entityManager;
@Transactional(transactionManager = "transactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void createUser(SecondaryUser user) {
entityManager.getDelegate().persist(user);
}
@Transactional(transactionManager = "transactionManager", readOnly = true)
public SecondaryUser getUserById(Long id) {
return entityManager.getDelegate().find(SecondaryUser.class, id);
}
}
```
阅读全文