How to enable hibernate filter for sessionFactory.getCurrentSession()?

限于喜欢 提交于 2019-11-28 05:34:11

The solution you have is pretty simple, but I'm guessing what you are trying for is to make it so that you don't have to provide a "getSession" implementation in each of your DAOs. Ultimately your method of implementing this is going to depend on how flexible you want to be with this filter. Here's two ways I might solve this.

The simplest way would be to simply make your UserDAOImpl extend a new base class that contains the "getSession" logic in it. This method would allow you to reduce code in that you would have this filter logic applied in most cases, but then you could override the filtering when you need to.

You could create something like this:

public class BaseDAO
{

    // ... possibly some other methods and variables

    @Autowired(required = true)
    private SessionFactory sessionFactory;

    protected Session getSession()
    {
        //Your session filter logic above
    }
}

Now you could just have your UserDAOImpl subclass this and get a session when it needs to do something. This is a very simple way to do what you are looking for, but it isn't foolproof. If you are writing a framework for others to use, then what would stop them from simply getting their own reference to your SessionFactory by having Spring inject it and then they could get an unfiltered Session? You might want this in certain circumstances for administrative processes that can act on all data, but the next way I'll describe should prevent this from happening.

This second way to solve the problem involves using AOP to wrap the getSession method of SessionFactory with your logic to apply the filter before the session is returned. This method means that even if someone gets a reference to your SessionFactory themselves, they will still have this filtering logic applied.

First, if you aren't familiar with AOP in spring have a look at the reference http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html. I'm going to use the schema based method to apply advice to Hibernate, because we don't want to modify the source of Hibernate. ;) You can find the specifics of this method at http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-schema.

First, make sure you have the following schema and aop:config section in your application context XML for spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans ...
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        ...
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    ...

<aop:config>
    <aop:aspect id="forceFilter" ref="sessionFilterAdvice">
        <aop:pointcut id="hibernateSessionFactoryGetSession"
            expression="execution(* org.hibernate.SessionFactory.openSession(..))" />
        <aop:after-returning method="setupFilter"
            pointcut-ref="hibernateSessionFactoryGetSession" returning="session" />
    </aop:aspect>
</aop:config>

    ...
</beans>

Next, you need to add a bean to your project to implement the sessionFilterAdvice bean we reference above with the aop:aspect tag. Create the following class:

package net.grogscave.example;

import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

@Service
public class SessionFilterAdvice
{
    public void setupFilter(Session session)
    {
        Session session = sessionFactory.getCurrentSession();
        Filter filter = session.enableFilter("restrictToCurrentCompany");
        filter.setParameter("currentCompanyNumber", UserUtils.getCurrentCompany());
    }
}

The final thing to make sure of is that your project includes the spring-aop jar and the aspectjweaver jar. I don't know if you use dependency management or not, but you somehow need to get those jars into your project classpath.

You should now be able to recompile your project, and now any calls to any of the openSession methods on classes that implement SessionFactory will add your filter to them.

Hibernate hbm file: Declare filter in your hbm file. Here filterByFacilityIDs is a filter and facilityIDsParam is a List< String > type parameter.

<hibernate-mapping package="com.ABC.dvo">
 <class name="ItemMasterDVO" table="Item_Master">
  ....
<set name="inventoryTaxesSet" inverse="true" cascade="all">
<key column="item_ID" />
<one-to-many class="InventoryTaxesDVO" />
    <filter name="filterByFacilityIDs" condition="Facility_ID in(:facilityIDsParam)"/>  
</set>
</class>
<filter-def name="filterByFacilityIDs">
 <filter-param name="facilityIDsParam" type="string"/>
</filter-def>
</hibernate-mapping>

** Java class **

public List<ItemMasterDVO> getItemMaster(String[] itemIDs, String[] facilityIDs){
    Session session = getSessionFactory().getCurrentSession();
    Criteria criteria = session.createCriteria(ItemMasterDVO.class)
        .add(Restrictions.in("itemNumber", itemIDs))
        .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    if(facilityIDs!=null && facilityIDs.length>0){          
        org.hibernate.Filter filter = session.enableFilter("filterByFacilityIDs");
        filter.setParameterList("facilityIDsParam", facilityIDs);
    }   
    criteria.addOrder(Order.asc("itemNumber"));
    List<ItemMasterDVO> result = criteria.list(); 
    return result;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!