我有一个带有2个数据库配置的Spring Boot项目。
主数据库配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(transactionManagerRef = "primaryTransactionManager", entityManagerFactoryRef = "primaryEntityManagerFactory", basePackages = { "com.example.repository.primary" })
public class PrimaryDbConfig {
@Primary
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.primary.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "primaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("primaryDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.example.domain.primary").persistenceUnit("primary-persistence-unit").build();
}
@Primary
@Bean(name = "primaryTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
中学:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "secondaryEntityManagerFactory", transactionManagerRef = "secondaryTransactionManager", basePackages = { "com.example.repository.secondary" })
public class SecondaryDbConfig {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.secondary.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("secondaryDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.example.domain.secondary").persistenceUnit("secondary-persistence-unit").build();
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
有加载第二个DB的实体:
@Entity
@Table(name = "users")
public class User {
@OneToMany(mappedBy = "user")
private List<Company> companies;
使用:
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
当我使用UserRepository
时,会检索到User
,但当我点击加载公司时,我会com.sun.jdi.InvocationException occurred invoking method.
- com.sun.jdi.InvocationException occurred invoking method。如果我将SecondaryDbConfig
更改为@Primary
或添加fetch = FetchType.EAGER
,则会按预期检索公司。我尝试添加@Transactional(transactionManager="secondaryTransactionManager")
,但它没有帮助。
我错过了什么?使用非主数据库配置时,延迟加载实体属性的正确方法是什么?
答案 0 :(得分:0)
尝试将@Transactional添加到检索公司列表的@Service方法或控制器中。
祝你好运!