2

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?

AlexZam
  • 1,147
  • 7
  • 18
  • 1
    No you don't need a session scoped object. Use a [`UserCredentialsDataSourceWrapper`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapter.html) and set the credentials on each request. Don't try to work with a session or other scoped entity manager. Or use the build in multi tenancy support for hibernate which also supports this out-of-the-box. – M. Deinum Oct 02 '15 at 05:55
  • Oh! Wow. Could you write it as an answer? I'll then accept it. – AlexZam Oct 02 '15 at 15:41

1 Answers1

1

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.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224