我可以知道如何为EntityManager设置默认值吗?例如,我希望EntityManager默认为“ A”,而不将行@PersistenceContext
修改为@PersistenceContext(unitName="A")
。我需要这样做,因为我无法编辑@PersistenceContext的行(其他项目的jar文件)。我尝试了@Primary,但是它不起作用。
// editable
@Bean(name = "A")
@Primary
public LocalContainerEntityManagerFactoryBean emfA() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
...
em.setPersistenceUnitName("A");
...
return em;
}
// editable
@Bean(name = "B")
public LocalContainerEntityManagerFactoryBean emfB() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
...
em.setPersistenceUnitName("B");
...
return em;
}
// not editable
@PersistenceContext
private EntityManager em;
答案 0 :(得分:0)
其中一个Spring员工在exactly how to do this上进行了演示。看来您将需要确切指定应在其中应用实体管理器的包。您需要在以下位置执行此操作:
@EnableJpaRepositories
具有basePackages
或basePackageClasses
属性,并且... EntityManagerFactoryBuilder#packages
构建器调用在他的示例中,看起来像:
@EnableJpaRepositories(
entityManagerFactoryRef = "orderEntityManager",
transactionManagerRef = "orderTransactionManager",
basePackageClasses = Order.class)
和
@Bean
public LocalContainerEntityManagerFactoryBean orderEntityManager(
JpaProperties orderJpaProperties) {
EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(
orderJpaProperties);
return builder
.dataSource(orderDataSource())
.packages(Order.class)
.persistenceUnit("ordersDs")
.build();
}