Different hibernate session for the same injected EntityManager

Posted on

I hope that someone can explain to me what could just be me having a misunderstanding.
We need some additional filtering on certain entities and I am using Hibernate @Filter(Def) annotations to define those. I need to enable these filters so I need to have access to the Hibernate session object and enable them. In order to do this (and if there is a better way, please let me know) I wrote an EntityManager Producer as follows:
Inject the EntityManager from the container
have a qualified 'produces' method that retrieves the session and enables the filter and returns the updated EM

public class EntityManagerProducer {
    @PersistenceContext(unitName = "nsfsApp")
    private EntityManager em;

    public EntityManager getEntityManager() {

        Session s = em.unwrap(Session.class);
        return em;

  // No dispose method, container will clean up the EM.

I noticed however that sometimes the filter was not applied and when I added log statements that would log the hashCode of both the entity manager and the HibernateSession it showed that when my request was going through the layers of EJBs and CDIs, the EM stayed the same but the Session object would change.
The 'fix' is that instead of injecting an EntityManager, I inject the EntityManagerFactory and use that to create a new EM, set the filter and return this newly created EM.
I just don't understand why the first implementation was not working.