gpt4 book ai didi

java - 在 Spring Boot 中获取 EntityManager 的句柄

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:49 31 4
gpt4 key购买 nike

有什么方法可以获得给定实体对象的 EntityManager 句柄吗?我正在使用带有 JPA starter 的 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;

没有运气。

最佳答案

这取决于您如何配置它,但您是否尝试过使用与创建它的工厂相对应的限定符注入(inject)EntityManager

这里是 a sample project with two data sources .如果你想为订单注入(inject)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;

检查项目的配置以获取更多详细信息。

关于java - 在 Spring Boot 中获取 EntityManager 的句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32020249/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com