在Spring Boot中获取EntityManager的句柄 [英] Obtaining handle to EntityManager in Spring Boot
问题描述
是否有任何方法可以获取给定实体对象的EntityManager句柄?我将Spring Boot 1.2.3与JPA Starter结合使用,并且进一步使用@configuration
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
我已经检查了 [已解决]对BOOTING BOOT的entityManager访问权限,但它没有似乎没有回答这个问题.
I've checked [resolved]SPRING BOOT access to entityManager and it doesn't seem to answer the question.
谢谢.
我添加了有关如何定义数据源的描述:
@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();
}
}
在我的application.yml中,我有以下部分
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...
到目前为止,我已经尝试了@Stephane的两个建议,但得到了NoSuchBeanDefinitionException
So far I've tried both of @Stephane's suggestions but I get NoSuchBeanDefinitionException
假设我的实体称为Customer
,然后我尝试了
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) {
...
}
}
但是我也尝试过
@PersistenceContext(unitName = "customer") // also tried "customers" and "first_datasource"
private EntityManager entityManager;
没有运气.
推荐答案
这取决于您如何进行配置,但是否尝试过使用与创造它的工厂?
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?
这是具有两个数据源的示例项目.如果要按订单注入EntityManager
,只需在项目的任何Spring bean中执行以下操作
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) {
...
}
}
对于客户,请使用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.
这篇关于在Spring Boot中获取EntityManager的句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!