I tried to do multi-tenancy with Hibernate 3.
Each table has a SystemId column to distinguish between tenants.
I added a Hibernate filter to the JPA entity that adds the SystemId column to the search condition.
I added the following annotations to Configuration to use my own Repository factory.
@EnableJpaRepositories(basePackages = "com.example.dataaccess.repositories",
repositoryFactoryBeanClass = PrimaryRepositoryFactoryBean.class)
PrimaryRepositoryFactoryBean.class
public class PrimaryRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends JpaRepositoryFactoryBean<T, S, ID> {
@Autowired //This child has a SystemId
private CurrentAppUserDetailsProvider currentAppUserDetailsProvider;
@Override //Returns RepositoryFactory
protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
return new MyRepositoryFactory(entityManager, currentAppUserDetailsProvider);
}
private static class MyRepositoryFactory<E, I extends Serializable> extends JpaRepositoryFactory {
private final EntityManager entityManager;
private final CurrentAppUserDetailsProvider currentAppUserDetailsProvider;
public MyRepositoryFactory(EntityManager entityManager,
CurrentAppUserDetailsProvider currentAppUserDetailsProvider) {
super(entityManager);
this.entityManager = entityManager;
this.currentAppUserDetailsProvider = currentAppUserDetailsProvider;
}
@Override
protected Object getTargetRepository(RepositoryMetadata metadata) {
Object repository = super.getTargetRepository(metadata);
SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class);
Session session = sessionFactory.getCurrentSession(); //Exception occurred! !!
session.enableFilter("SYSTEM_ID_FILTER")
.setParameter("systemId", getSystemId());
return repository;
}
private int getSystemId() {
return currentAppUserDetailsProvider
.getCurrentAppUserDetails()
.getSystemId();
}
}
}
At the time of instantiating the Repository, there is no Session because the transaction has not started.
It's natural, isn't it?
Recommended Posts