【发布时间】:2015-11-08 07:27:58
【问题描述】:
有什么方法可以获取给定实体对象的 EntityManager 句柄?我正在使用带有 JPA 启动器的 spring boot 1.2.3,并且我正在使用 @configuration 进一步明确配置多个数据源
我检查了[resolved]SPRING BOOT access to 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;
没有运气。
【问题讨论】:
-
如果不了解您是如何配置 JPA 数据库的,这有点难说。通常你应该可以使用
@PersistenceContext并且你很高兴。您能告诉我们您是如何配置数据库的吗? -
谢谢我知道了。仅当您需要主数据源以外的数据源时,您才需要提供 unitName。省略单元名称可以让您获得最终为我的目的工作的主要实体管理器。
标签: java spring-boot jpa spring-data-jpa spring-data