我使用spring数据并hibernate@ Filter / @ FilterDef来过滤软删除的实体。似乎springRepository.findOne(id)总是返回值,即使id被软删除。此方法以及通过外键搜索其他字段的where子句中不包含过滤器。在这种情况下是否可以启用过滤器,使其可以用作@Where注释?
我有同样的问题。我已经通过实现HibernatePersistenceProvider和HibernateEntityManagerFactory类解决了它。
public class FilterEnableHibernatePersistenceProvider extends HibernatePersistenceProvider { @Override public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { return wrapEntityManagerFactory(super.createEntityManagerFactory(persistenceUnitName, properties)); } @Override public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { return wrapEntityManagerFactory(super.createContainerEntityManagerFactory(info, properties)); } private EntityManagerFactoryWrapper wrapEntityManagerFactory(EntityManagerFactory entityManagerFactory) { return entityManagerFactory == null ? null : new EntityManagerFactoryWrapper(entityManagerFactory); } public static class EntityManagerFactoryWrapper implements HibernateEntityManagerFactory { //This is where the filters are being activated protected EntityManager initSession(EntityManager entityManager) { Session session = ((HibernateEntityManager) entityManager).getSession(); if (session.getEnabledFilter(FILTER_NAME) == null) { Filter activeFilter = session.enableFilter(FILTER_NAME); activeFilter.setParameter("some_field", some_value); } return entityManager; } // wrapp other methods }
在每次会话初始化之后,将启用过滤器。现在,您需要将FilterEnableHibernatePersistenceProvider添加到您的配置类中:
@Configuration public class JpaConfiguration { @Bean() public LocalContainerEntityManagerFactoryBean entityManagerFactory(){ LocalContainerEntityManagerFactoryBean emFactory = new LocalContainerEntityManagerFactoryBean(); emFactory.setPersistenceProviderClass(FilterEnableHibernatePersistenceProvider.class); //yours configuration }