M
M
MaxLich2019-05-08 16:09:46
Java
MaxLich, 2019-05-08 16:09:46

How to specify EntityManagerFactory name in @PersistenceContext?

Hello. How to specify the name of a specific EntityManagerFactory when using @PersistenceContext?
Code like this:

@PersistenceContext
    private EntityManager em;

And the bean initialization code:
// ----- ADM ------

    @Bean(name = "dataSourceNsi")
    public DataSource dataSourceAdm() throws NamingException {
        return (DataSource) new JndiTemplate().lookup("java:comp/env/" + admJndiName);
    }


    @Bean(name = Constants.ADM_ENTITY_MANAGER_FACTORY_NAME, destroyMethod = "")
    public LocalContainerEntityManagerFactoryBean admEntityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSourceAdm());
        em.setPackagesToScan(admPackagesToScan);

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernatePropertiesAdm());

        return em;
    }

    @Bean(name = Constants.ADM_TRANSACTION_MANAGER_NAME, destroyMethod = "")
    public PlatformTransactionManager admTransactionManager() throws NamingException {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(admEntityManagerFactory().getObject());
        return transactionManager;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MaxLich, 2019-05-08
@MaxLich

It seems to work like this:

@PersistenceContext(unitName = Constants.ADM_ENTITY_MANAGER_FACTORY_NAME)
    private EntityManager em;

@Bean(name = Constants.ADM_ENTITY_MANAGER_FACTORY_NAME, destroyMethod = "")
    public LocalContainerEntityManagerFactoryBean admEntityManagerFactory() throws NamingException {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSourceAdm());
        em.setPackagesToScan(admPackagesToScan);

          em.setPersistenceUnitName(Constants.ADM_ENTITY_MANAGER_FACTORY_NAME);

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernatePropertiesAdm());

        return em;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question