[Java] [Spring] Record of failure to enable Hibernate filter when instantiating Spring Data Repository

Motivation

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.

Record of failure

Use your own Repository factory

I added the following annotations to Configuration to use my own Repository factory.

@EnableJpaRepositories(basePackages = "com.example.dataaccess.repositories",
        repositoryFactoryBeanClass = PrimaryRepositoryFactoryBean.class)

Created Repository factory

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();
        }

    }
}

Details of the failure

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

[Java] [Spring] Record of failure to enable Hibernate filter when instantiating Spring Data Repository
Use jenv to enable multiple versions of Java
Things to be aware of when writing Java
[Java] Things to be aware of when outputting FizzBuzz
Things to be aware of when writing code in Java