Search code examples
javaspringhibernatespring-mvchibernate-entitymanager

HTTP session scoped EntityManagerFactory in Spring


I have a need of using separate EntityManagerFactory for each HTTP session in Spring 4. It is because of authentication by DB login-password. So I make session-scoped DataSource and EntityManagerFactory like this:

@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public FactoryBean<EntityManagerFactory> entityManagerFactory() throws SQLException {
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();        
    factoryBean.setDataSource(dataSource());
    factoryBean.setPersistenceProviderClass(HibernatePersistence.class);
    factoryBean.setPersistenceUnitName("db");
    return factoryBean;
}

Then I try to inject it into singleton:

@PersistenceContext
private EntityManager entityManager;

But I'm getting an error:

NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: scopedTarget.entityManagerFactory,entityManagerFactory

What could be done to inject it right?


Solution

  • You don't need (or want) a session scoped EntityManagerFactory.

    Either use a DataSource that supports setting credentials for the execution thread, like the UserCredentialsDataSourceAdapter or use the multi tenancy support that is build into hibernate.