简体   繁体   中英

How to set default value for EntityManager

May I know how to set default value for EntityManager? For example, I want EntityManager default to be "A" without modifying the line @PersistenceContext to @PersistenceContext(unitName="A") . I need to do this because I am not able to edit the line of @PersistenceContext (a jar file from other project). I tried @Primary but it does not work.

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

One of the Spring guys made a demo on exactly how to do this . It looks like you will need to specify the packages exactly where the entity manager should be applied. You will need to do that in:

  1. @EnableJpaRepositories with the basePackages or basePackageClasses properties and also...
  2. The EntityManagerFactoryBuilder#packages builder call

In his example, looks like:

@EnableJpaRepositories(
        entityManagerFactoryRef = "orderEntityManager",
        transactionManagerRef = "orderTransactionManager",
        basePackageClasses = Order.class)

and

@Bean
public LocalContainerEntityManagerFactoryBean orderEntityManager(
        JpaProperties orderJpaProperties) {
    EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(
            orderJpaProperties);
    return builder
            .dataSource(orderDataSource())
            .packages(Order.class)
            .persistenceUnit("ordersDs")
            .build();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM