hibernate过滤器

转自:http://42087743.iteye.com/blog/305219

Hibernate提供了对类使用预先定义的过滤器条件的功能,并提供了专门的Filter类.

[list]
  • 首先在需要过滤的model类的hbm.xml中:
    Java代码 收藏代码
    1. <classname="com.u2map.model.oneToOne.Pwd">
    2. <idname="id"column="id"type="integer">
    3. <generatorclass="foreign">
    4. <paramname="property">member</param>
    5. </generator>
    6. </id>
    7. <propertyname="pwd"column="pwd"type="string"></property>
    8. <one-to-onename="member"constrained="true"class="com.u2map.model.oneToOne.Member"></one-to-one>
    9. //过滤器配置
    10. <filtername="myFilter"condition="pwdlike:myFilterParam"/>
    11. </class>
    12. //过滤器配置
    13. <filter-defname="myFilter">
    14. <filter-paramname="myFilterParam"type="string"/>
    15. </filter-def>

    [/list]

    [list]
  • 其次,在testcase中加上过滤:
    Java代码 收藏代码
    1. //使用过滤器
    2. session.enableFilter("myFilter").setParameter("myFilterParam","%a%");
    3. Queryquery=session.createQuery("fromPwdpwherep.id=:id");
    4. query.setParameter("id",3);
    5. Pwdmember=null;
    6. try{
    7. member=(Pwd)query.uniqueResult();
    8. }catch(HibernateExceptione){
    9. e.printStackTrace();
    10. }
    11. Assert.assertEquals(member.getId(),3);
    12. Assert.assertEquals(member.getPwd(),"abc");

    [/list]

    [list]
  • 查看下hibernate生成的sql语句,证明filter已经加上:
    Java代码 收藏代码
    1. Hibernate:selectpwd0_.idasid1_,pwd0_.pwdaspwd1_fromPwdpwd0_wherepwd0_.pwdlike?andpwd0_.id=?
  • 你可能感兴趣的:(Hibernate)