I'm attempting to use Hibernate 4's Entity level @Filter
's with Spring data repositories inside of a Spring Boot project. My end goal is to implement a generic soft delete with something a bit more flexible then Hibernate's @Where
annotation.
After a bit of a struggle I've come to the possibly naive solution that this could be handled using an @Aspect
I set up a Spring managed aspect with the aim to intercept calls to the shared EntityManager
and enable the appropriate filter.
I played around with a few different pointcuts and it looks like execution(public * javax.persistence.EntityManager.find(..))
is an ok place to bind this advice.
@Aspect
@Component
public class HibernateFilterInterceptor {
private final EntityManager entityManager;
private final PlatformTransactionManager platformTransactionManager;
@Autowired
public HibernateFilterInterceptor(EntityManager entityManager, PlatformTransactionManager platformTransactionManager) {
this.entityManager = entityManager;
this.platformTransactionManager = platformTransactionManager;
}
@Before("execution(public * javax.persistence.EntityManager.find(..))")
public void beforeFind(){
}
From the Hibernate docs/examples it seems like I should be able to enable the filter using something like entityManager.unwrap(Session.class).enableFilter("filter").setParameter("foo", 1);
So to test I defined a simple filter on a single entity.
@FilterDef(name = "status", parameters = @ParamDef(name = "status", type = "integer"))
@Filters(
@Filter(name = "status", condition = ":status = status")
)
public class Entity{
And enabled it in my advice
@Before("execution(public * javax.persistence.EntityManager.find(..))")
public void beforeFind(){
entityManager.unwrap(Session.class).enableFilter("status").setParameter("status", 1);
}
And the filter is not applied.