简体   繁体   中英

Hibernate Filters with JPA EntityManagerFactory and Spring

I have a jersey + spring application that is using EntityManagerFactory and spring JpaTransactionManager to handle the db manipulations. The JPA implementation is hibernate.

I would like to know is there a way to enable hibernate filters in this scenario.

I tried extending org.springframework.orm.jpa.JpaTransactionManager and overriding

@Override
protected EntityManager createEntityManagerForTransaction() {
    EntityManager manager = super.createEntityManagerForTransaction();

    Session session = manager.unwrap(Session.class);

    return manager;
}

But I am not sure that this method is called at the right place.

EDIT: I am using spring JpaRepositories to persist/query entities.

I found an answer for this problem. It seems like other people are still struggling with this, I will post my solution.

I am enabling the filters that I need in business service methods that are marked as @Transactional (that is important).

In your service, inject the entity manager factory:

 @Autowired
 private EntityManagerFactory entityManagerFactory;

Inside the @Transactional method obtain the entity manager from the transactionManager, unwrap it to hibernate session and enable the filters that you need. This is done as follows:

    //Obtain the entity manager for the current transaction
    EntityManagerHolder holder = (EntityManagerHolder) TransactionSynchronizationManager.getResource(entityManagerFactory);
    EntityManager entityManager = holder.getEntityManager();

    //Unwrap to get the underlying hibernate session
    Session hibernateSession = entityManager.unwrap(Session.class);

    //Configure your filters
    Filter publishedAfterFilter = hibernateSession.enableFilter("...");
    publishedAfterFilter.setParameter("...", ...);
    publishedAfterFilter.validate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM