Global hibernate filter on all database queries

后端 未结 1 1529
夕颜
夕颜 2020-12-30 11:51

I am using Spring MVC and Hibernate for my web application. I am looking for a way to create a global hibernate filter of sorts that would apply to each query in my DAO clas

相关标签:
1条回答
  • 2020-12-30 12:39

    Putting out the way I handled this down here. Below is based on the discussion with @Rp- and suggestions made here.

    Three major elements went into configuring this:
    - Spring's session scoped beans
    - package-info.java
    - Spring AOP



    I created a session scoped Spring bean that will hold my user selected variable. The variable would get modified upon user's request through a spring Controller mapping method. Being held in a spring managed bean, I have access to the session variable anywhere in my application by virtue of spring's dependency injection.

    @Component
    @Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
    public class SessionParam implements Serializable{
    
      private String sessParam;
    ..
    ..
    }
    

    Next I define my hibernate filter at package level. This is done in package-info.java file. All entities in this package thus inherit this filter.

     @FilterDef(name="GLOBAL_FILTER",   parameters = {@ParamDef(name="sessParam", type="string")}, 
                                        defaultCondition = "sessParam = :sessParam")
    
    package com.company.app.entity;
    import org.hibernate.annotations.FilterDef;
    import org.hibernate.annotations.FilterDefs;
    import org.hibernate.annotations.ParamDef;
    


    Entities in the package are annotated with hibernate's @Filter annotation as below:

    @Entity
    @Filter(name="GLOBAL_FILTER")
    @Table(name = "TABLE_XYZ", schema = "SCHEMA_ABC")
    public class TableXyz implements Serializable {
    ...
    }
    

    Lastly, all DAO queries are intercepted using an AspectJ aspect on hibernate's Session Factory's getCurrentSession() method.

    Below is the Aspect class.

    @Aspect
    @Component
    public class GlobalFilter {
    
        @Autowired
        SessionParam sessionParam;
    
    
        @Pointcut("execution(* org.hibernate.SessionFactory.getCurrentSession(..))")
        protected void hibernateSessionFetch(){
    
        }
    
        @AfterReturning(pointcut = "hibernateSessionFetch()", returning = "result")
        public void enableGlobalFilter(JoinPoint joinPoint, Object result){
    
            Session session = (Session) result;
    
            session.enableFilter("GLOBAL_FILTER").setParameter("sessParam", sessionParam.getSessParam());
    
        }
    }
    

    All queries on entities with "GLOBAL_FILTER" now have a conditional check on the required variable. No explicit conditional checks in each query is required in the DAO methods.

    0 讨论(0)
提交回复
热议问题