在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(); } }
在我的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;
检查项目配置以获取更多详细信息。