hibernate过滤器:Hibernate过滤器使用窍门

  本文向大家介绍Hibernate过滤器可能好多人还不了解Hibernate过滤器没有关系看完本文你肯定有不少收获希望本文能教会你更多东西

  Hibernate3新增了对某个类或者集合使用预先定义Hibernate过滤器条件(filter criteria)功能过滤器条件相当于定义个 非常类似于类和各种集合上“where”属性约束子句但是过滤器条件可以带参数

  应用可以在运行时决定是否启用给定Hibernate过滤器以及使用什么样参数值 过滤器使用方法很像数据库视图只不过是在应用中确定使用什么样参数

  要使用过滤器必须首先在相应映射节点中定义而定义个过滤器要用到位于<hibernate-mapping/> 节点的内<filter-def/>节点:

<filter-def name="myFilter"> 
 
    <filter-param name="myFilterParam" type=""/> 
 
 </filter-def> 


  定义好的后就可以在某个类中使用这个过滤器:

< name="myClass" ...> 
 
    ...  
 
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> 
 
</> 


  也可以在某个集合使用它:

< ...> 
 
    <filter name="myFilter" condition=":myFilterParam = MY_FILTERED_COLUMN"/> 
 
</> 


  可以在多个类或集合中使用某个过滤器;某个类或者集合中也可以使用多个过滤器

  Session对象中会用到思路方法有:enableFilter(String filterName), getEnabledFilter(String filterName), 和 disableFilter(String filterName). Session中默认是不启用过滤器必须通过Session.enabledFilter思路方法显式启用该思路方法返回被启用Filter例子以上文定义过滤器为例:

session.enableFilter("myFilter").Parameter("myFilterParam", "some-value"); 

  注意org.hibernate.Filter思路方法允许链式思路方法(类似上面例子中启用Filter的后设定Filter参数这个“思路方法链”) Hibernate其他部分也大多有这个特性

  下面是个比较完整例子使用了记录生效日期模式过滤有时效数据:

<filter-def name="effectiveDate"> 
 
    <filter-param name="asOfDate" type="date"/> 
 
</filter-def> 
 
 
 
< name="Employee" ...> 
 
...  
 
    <many-to-one name="department" column="dept_id" ="Department"/> 
 
    <property name="effectiveStartDate" type="date" column="eff_start_dt"/> 
 
    <property name="effectiveEndDate" type="date" column="eff_end_dt"/> 
 
...  
 
    <!--  
 
        Note that this assumes non-terminal records have an eff_end_dt  to  
 
        a max db date for simplicity-sake  
 
 
 
        注意为了简单起见此处假设雇用关系生效期尚未结束记录eff_end_dt字段值等于数据库最大日期  
 
    --> 
 
    <filter name="effectiveDate" 
 
            condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> 
 
</> 
 
 
 
< name="Department" ...> 
 
...  
 
    < name="employees" lazy="true"> 
 
        <key column="dept_id"/> 
 
        <one-to-many ="Employee"/> 
 
        <filter name="effectiveDate" 
 
                condition=":asOfDate BETWEEN eff_start_dt and eff_end_dt"/> 
 
    </> 
 
</> 




  定义好后如果想要保证取回都是目前处于生效期记录只需在获取雇员数据操作的前先开启过滤器即可:

Session session = ...;  
 
session.enabledFilter("effectiveDate").Parameter("asOfDate",  Date);  
 
List results = session.createQuery("from Employee as e where e.salary > :targetSalary")  
 
         .Long("targetSalary",  Long(1000000))  
 
         .list;  


  在上面HQL中虽然我们仅仅显式使用了个薪水条件启用了过滤器查询将仅返回那些目前雇用 关系处于生效期并且薪水高于百万美刀雇员数据

  注意:

  如果你打算在使用外连接(或者通过HQL或load fetching)同时使用过滤器要注意条件表达式方向(左还是右) 最安全方式是使用左外连接(left outer joining)并且通常来说先写参数 然后是操作符最后写数据库字段名



Tags:  过滤器使用 使用选定的过滤器 hibernate使用 hibernate过滤器

延伸阅读

最新评论

发表评论