在 Spring Boot 中获取 EntityManager 的句柄

有没有办法获取给定实体对象的 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();
    }
}

在我的应用程序中.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;

没有运气。


答案 1

这取决于你如何配置它,但你是否尝试过注入一个与创建它的工厂相对应的限定符?EntityManager

下面是一个包含两个数据源的示例项目。如果你想注入 for 订单,只需在项目的任何 Spring bean 中执行以下操作EntityManager

@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;

有关更多详细信息,请检查项目的配置。


答案 2

推荐