[英]Obtaining handle to EntityManager in Spring Boot
有沒有辦法獲得給定實體對象的EntityManager句柄? 我正在使用帶有JPA啟動器的spring boot 1.2.3,我還使用@configuration
顯式配置了多個數據源
我檢查了[已解決] SPRING BOOT對entityManager的訪問權限,似乎沒有回答這個問題。
謝謝。
編輯:我添加了如何定義數據源的說明:
@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中,我有以下部分
first.datasource:
name: 'first_datasource',
#other attributes...
second.datasource:
name: 'second_datasource',
#other attributes...
third.final.datasource:
name: 'first_datasource',
#other attributes...
到目前為止,我已經嘗試了@ Stephane的兩個建議,但我得到了NoSuchBeanDefinitionException
假設我的實體名為Customer
然后我嘗試了
@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;
沒有運氣。
這取決於你是如何配置它的,但是你是否嘗試使用與創建它的工廠相對應的限定符注入 EntityManager
?
這是一個包含兩個數據源的示例項目 。 如果要為訂單注入EntityManager
,只需在項目的任何Spring bean中執行以下操作
@Service
public class FooService {
private final EntityManager entityManager;
@Autowired
public FooService(@Qualifier("orderEntityManager") EntityManager entityManager) {
...
}
}
對於客戶,請使用customerEntityManager
。
當然,您可以使用持久性單位名稱,即
@PersistenceContext(unitName = "customers")
private EntityManager entityManager;
@PersistenceContext(unitName = "orders")
private EntityManager entityManager;
檢查項目配置以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.