pas*_*ian 14 java jpa spring-data spring-data-jpa 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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的application.yml中,我有以下部分
first.datasource:
name: 'first_datasource',
#other attributes...
second.datasource:
name: 'second_datasource',
#other attributes...
third.final.datasource:
name: 'first_datasource',
#other attributes...
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试了@ Stephane的两个建议,但我得到了 NoSuchBeanDefinitionException
假设我的实体被调用Customer然后我试过了
@Service
public class FooService {
private final EntityManager entityManager;
@Autowired
public FooService(@Qualifier("customerEntityManager") EntityManager entityManager) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
但我也试过了
@PersistenceContext(unitName = "customer") // also tried "customers" and "first_datasource"
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)
没有运气.
Ste*_*oll 21
这取决于你是如何配置它的,但是你是否试过注入一个EntityManager与创建它的工厂相对应的限定符?
这是一个包含两个数据源的示例项目.如果要注入EntityManagerfor order,只需在项目的任何Spring bean中执行以下操作
@Service
public class FooService {
private final EntityManager entityManager;
@Autowired
public FooService(@Qualifier("orderEntityManager") EntityManager entityManager) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
对于客户,请使用customerEntityManager.
当然,您可以使用持久性单位名称,即
@PersistenceContext(unitName = "customers")
private EntityManager entityManager;
@PersistenceContext(unitName = "orders")
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)
检查项目配置以获取更多详细信息.
| 归档时间: |
|
| 查看次数: |
30002 次 |
| 最近记录: |