title: Hibernate Entity filters are not working if assigned in Event listeners and for some JPA methods in spring-data
body: <p>I am using jpa in my spring-boot project for CRUD operations. 
  Before doing any operation , I want to apply a filter.
  I want same filter to be applied for all my entities , so I have written a <code>EntityListener</code> which will enable filter on <code>PrePersist</code> , <code>PreLoad</code> and <code>PreRemove</code> events for entity under operation.</p>
  
  <p>Entity <code>Site</code> and may other entities extends <code>AOrganization</code> Class on which a filter is defined.
  I am enabling this filter in <code>EntityListener</code>. While filter is getting enabled here , it is not reflecting in resulting operation query.</p>
  
  <p>Please check my code below.</p>
  
  <p><strong>AOrganization.java</strong></p>
  
  <pre><code>import java.io.Serializable;
  
  import javax.persistence.JoinColumn;
  import javax.persistence.ManyToOne;
  import javax.persistence.MappedSuperclass;
  
  import org.hibernate.annotations.Filter;
  import org.hibernate.annotations.FilterDef;
  import org.hibernate.annotations.ParamDef;
  
      @MappedSuperclass
      @FilterDef(name = "OrgFilter", parameters = { @ParamDef(name = "allowedOrgIdList", type = "long") })
      @Filter(name = "OrgFilter", condition = "org_id in (:allowedOrgIdList)")
      public class AOrganization implements Serializable {
  
          @ManyToOne()
          @JoinColumn(name = "org_id", nullable = true)
          private Organization organization;
  
          public Organization getOrganization() {
              return organization;
          }
  
          public void setOrganization(Organization organization) {
              this.organization = organization;
          }
      }
  </code></pre>
  
  <p><strong>Site.java</strong></p>
  
  <pre><code>import javax.persistence.Column;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.Table;
  
  
  @Entity
  @Table(name = "site")
  public class Site extends AOrganization{
  
      private static final long serialVersionUID = 1L;
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "id")
      private long id;
  
      @Column(name = "site_name")
      private String siteName;
  
      @Override
      public String toString() {
          return "Site [id=" + id + ", siteName=" + siteName + "]";
      }
  
      public long getId() {
          return id;
      }
  
      public void setId(long id) {
          this.id = id;
      }
  
      public String getSiteName() {
          return siteName;
      }
  
      public void setSiteName(String siteName) {
          this.siteName = siteName;
      }
  }
  </code></pre>
  
  <p><strong>EntityListener.java</strong></p>
  
  <pre><code>import java.util.Arrays;
  
  import javax.annotation.PostConstruct;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.PersistenceUnit;
  
  import org.hibernate.Filter;
  import org.hibernate.Session;
  import org.hibernate.event.service.spi.EventListenerRegistry;
  import org.hibernate.event.spi.AbstractEvent;
  import org.hibernate.event.spi.EventType;
  import org.hibernate.event.spi.PreDeleteEvent;
  import org.hibernate.event.spi.PreDeleteEventListener;
  import org.hibernate.event.spi.PreLoadEvent;
  import org.hibernate.event.spi.PreLoadEventListener;
  import org.hibernate.event.spi.PreUpdateEvent;
  import org.hibernate.event.spi.PreUpdateEventListener;
  import org.hibernate.internal.SessionFactoryImpl;
  import org.springframework.stereotype.Component;
  
  
  @Component
  public class EntityListener implements PreLoadEventListener, PreUpdateEventListener, PreDeleteEventListener {
  
      @PersistenceUnit
      private EntityManagerFactory entityManagerFactory;
  
      @PostConstruct
      private void init() {
          SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
          EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
  
          registry.getEventListenerGroup(EventType.PRE_LOAD).appendListener(this);
          registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(this);
          registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(this);
      }
  
      @Override
      public void onPreLoad(PreLoadEvent event) {
          enableOrgFilter(event, event.getEntity());
      }
  
      @Override
      public boolean onPreUpdate(PreUpdateEvent event) {
          enableOrgFilter(event, event.getEntity());
          return false;
      }
  
      @Override
      public boolean onPreDelete(PreDeleteEvent event) {
          enableOrgFilter(event, event.getEntity());
          return false;
      }
  
      private void enableOrgFilter(AbstractEvent event, Object entity) {
  
          Class clazz = entity.getClass();
  
          boolean isExtendingAOrganization = isExtendingAOrganization(clazz);
          if (isExtendingAOrganization) {
              Session session = event.getSession();
  
              System.out.println(session);
  
              Filter filter = session.enableFilter("OrgFilter");
              filter.setParameterList("allowedOrgIdList", Arrays.asList(2l));
          }
      }
  
      private boolean isExtendingAOrganization(Class clazz) {
          boolean isExtendingFromAOrganization = false;
  
          if (AOrganization.class.isAssignableFrom(clazz)) {
              isExtendingFromAOrganization = true;
          }
  
          return isExtendingFromAOrganization;
      }
  
  }
  </code></pre>
  
  <p><strong>SiteServiceImpl.java</strong></p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  
  import javax.persistence.EntityManager;
  
  import org.hibernate.Filter;
  import org.hibernate.Session;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  
  
  @Service
  public class SiteServiceImpl implements SiteService {
  
      @Autowired
      private EntityManager entityManager;
  
      @Autowired
      private SiteRepository siteRepository;
  
      @Override
      public List&lt;Site&gt; getAllSites() {
          Iterable&lt;Site&gt; sites = siteRepository.findAll();
  
          List&lt;Site&gt; allSites = new ArrayList&lt;&gt;();
  
          sites.forEach(allSites::add);
  
          return allSites;
  
      }
  
      @Override
      public List&lt;Site&gt; getSiteBySiteName(String siteName) {
  
          Session session = entityManager.unwrap(Session.class);
  
          System.out.println(session);
  
  //      Filter filter = session.enableFilter("OrgFilter");
  //      filter.setParameterList("allowedOrgIdList", Arrays.asList(2l));
  
          List&lt;Site&gt; allSites = siteRepository.findBySiteName(siteName);
          return allSites;
      }
  
      @Override
      public Site updateSiteName(Long id,String siteName) {
  
          Session session = entityManager.unwrap(Session.class);
  
          System.out.println(session);
  
  //      Filter filter = session.enableFilter("OrgFilter");
  //      filter.setParameterList("allowedOrgIdList", Arrays.asList(2l));
  
          Site site = siteRepository.findById(id).get();
  
          List&lt;Site&gt; copy = siteRepository.findBySiteName(site.getSiteName());
  
          if(site == null)
              return null;
  
          site.setSiteName(siteName);
  
          siteRepository.save(site);
  
          return site;
      }
  
  }
  </code></pre>
  
  <p><strong>SiteRepository.java</strong></p>
  
  <pre><code>import java.util.List;
  import java.util.Optional;
  
  import org.springframework.data.repository.CrudRepository;
  import org.springframework.stereotype.Repository;
  
  
  
  @Repository
  public interface SiteRepository extends CrudRepository&lt;Site, Long&gt; {
  
      public List&lt;Site&gt; findBySiteName(String siteName);
  
      public Optional&lt;Site&gt; findById(Long id);
  }
  </code></pre>
  
  <p>If filter is enabled through <code>EntityListener</code>  , its not working. But if I enable filter in <code>SiteServiceImpl getSiteBySiteName</code> method, it works.</p>
  
  <p>Also , in <code>SiteServiceImpl</code>, filter changes are reflected only for <code>findBySiteName</code> method and not in  <code>findById</code> .</p>
  
  <p>Any idea why this is happening or alternate solution ?
   Thanks in advance.</p>