如何设置EntityManager的默认值

时间:2018-07-05 03:13:33

标签: java spring jpa spring-data-jpa

我可以知道如何为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;

1 个答案:

答案 0 :(得分:0)

其中一个Spring员工在exactly how to do this上进行了演示。看来您将需要确切指定应在其中应用实体管理器的包。您需要在以下位置执行此操作:

  1. @EnableJpaRepositories具有basePackagesbasePackageClasses属性,并且...
  2. 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();
}