我使用spring数据和hibernate @ Filter / @ FilterDef来过滤软删除的实体。看起来springRepository.findOne(id)总是返回值,即使id被软删除也是如此。过滤器不包含在此方法的where子句中,也不包含在另一个外键字段中进行搜索。在这种情况下是否可以启用过滤器,以便它可以作为@Where注释使用?
答案 0 :(得分:4)
我遇到了同样的问题。我通过实现HibernatePersistenceProvider和HibernateEntityManagerFactory类来解决它。
System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(tokens[0], tokens[1]);
每次会话初始化后,将启用过滤器。现在你需要将FilterEnableHibernatePersistenceProvider添加到你的配置类:
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
}