Search code examples
springentitymanager

Primary entity manager factory is not selected in Spring


There are two datasources configured. Primary em factory:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    basePackages = {"com.example.data.postgresql"},
    entityManagerFactoryRef = "postgreSqlEntityManagerFactory",
    transactionManagerRef = "postgreSqlEntityTransactionManager"
)
public class PostgreSqlJpaConfig {
...
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean postgreSqlEntityManagerFactory(
        @Qualifier("postgreSqlDataSource") DataSource dataSource,
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(dataSource).packages("com.example.postgresql").build();
}

Secondary em factory:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = {"com.example.data.greenplum"},
        entityManagerFactoryRef = "greenPlumEntityManagerFactory",
        transactionManagerRef = "greenPlumEntityTransactionManager"
)
public class GreenPlumJpaConfig {

@Bean
public LocalContainerEntityManagerFactoryBean greenPlumEntityManagerFactory(
        @Qualifier("greenPlumDataSource") DataSource dataSource,
        EntityManagerFactoryBuilder builder){
    return builder.dataSource(dataSource).packages("com.example.greenplum").build();
}

Services lays in com.example.service. Sometimes they use entity manager, and Spring can't choose between two:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field entityManager in ... required a single bean, but 2 were found:

I can manually add a qualifier to the every em injection to make it work,

@Autowired
public void setEntityManager(@Qualifier("postgreSqlEntityManagerFactory") EntityManager entityManager) {
    this.entityManager = entityManager;
}

but there are 120+ em injections in the app so I hope there should be another way to tell Spring to use the default primary em in all cases where it is not specified explicitly.


Solution

  • The problem was the outdated Spring Boot. Upgrade to 2.6.2 solved the issue.