Obtaining handle to EntityManager in Spring Boot

2019-03-18 22:00发布

Is there any way to get a handle to the EntityManager for a given entity object? I'm using spring boot 1.2.3 with JPA starter and i'm further explicitly configuring multiple data sources with @configuration

I've checked [resolved]SPRING BOOT access to entityManager and it doesn't seem to answer the question.

Thanks.

EDIT: I added description of how my data sources are defined:

@Component
@Configuration
public class DataSources {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="first.datasource")
    public DataSource getPrimaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="second.datasource")
    public DataSource getSecondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="third.final.datasource")
    public DataSource getThirdFinalDataSource() {
        return DataSourceBuilder.create().build();
    }
}

In my application.yml I have the following sections

first.datasource:
  name: 'first_datasource',
  #other attributes...
second.datasource:
  name: 'second_datasource',
  #other attributes...
third.final.datasource:
  name: 'first_datasource',
  #other attributes...

So far I've tried both of @Stephane's suggestions but I get NoSuchBeanDefinitionException

Let's say my entity is called Customer then I tried

@Service
public class FooService {

    private final EntityManager entityManager;

    @Autowired
    public FooService(@Qualifier("customerEntityManager") EntityManager entityManager) {
        ...
    }

}

But I also tried

@PersistenceContext(unitName = "customer") // also tried "customers" and "first_datasource"
private EntityManager entityManager;

with no luck.

1条回答
聊天终结者
2楼-- · 2019-03-18 22:08

It depends how you've been configuring this but have you tried to inject the EntityManager with a qualifier that corresponds to the factory that created it?

Here is a sample project with two data sources. If you want to inject the EntityManager for order, just do the following in any Spring bean of the project

@Service
public class FooService {

    private final EntityManager entityManager;

    @Autowired
    public FooService(@Qualifier("orderEntityManager") EntityManager entityManager) {
        ...
    }

}

For customer, use the customerEntityManager.

Of course you can use the persistent unit name instead, that is

@PersistenceContext(unitName = "customers")
private EntityManager entityManager;

@PersistenceContext(unitName = "orders")
private EntityManager entityManager;

Check the configuration of the project for more details.

查看更多
登录 后发表回答