Hibernate_过滤器

过滤器的定义:

 1 <hibernate-mapping>
 2     <class name="com.sunflower.yuan.pojo.Family" table="family">
 3         <id name="id" column="id">
 4             <generator class="uuid"></generator>
 5         </id>
 6 
 7         <property name="username" column="username" type="string"></property>
 8         <property name="address" column="address" type="string"></property>
 9         <property name="cost" column="cost" type="double"></property>
10 
11         <!-- 声明使用过滤器,规定过滤器过滤内容 -->
12         <filter name="costFilter" condition="cost>:inputCost"></filter>
13     </class>
14 
15     <!-- 定义过滤器,带参数cost -->
16     <filter-def name="costFilter">
17         <filter-param name="inputCost" type="double" />
18     </filter-def>
19 </hibernate-mapping>

过滤器的使用:

 1 public class Test {
 2     public static void main(String[] args) {
 3         Session session = HibernateUtil.getSession();
 4         Transaction ts = null;
 5 
 6         try {
 7             ts = session.beginTransaction();
 8 
 9             Query query = session.createQuery("from Family");
10 
11             Filter filter = session.enableFilter("costFilter");
12             filter.setParameter("inputCost", new Double(550));
13 
14             List<Family> list = query.list();
15             for (Family family : list) {
16                 System.out.println("Username:" + family.getUsername()
17                         + ", Cost:" + family.getCost());
18             }
19 
20             ts.commit();
21         }
22         catch (Exception e) {
23             if (ts != null && ts.isActive())
24                 ts.rollback();
25             e.printStackTrace();
26         }
27         finally {
28             HibernateUtil.closeSession(session);
29         }
30     }
31 }

 

第11行是激活过滤器,第12行是传递过滤器参数值。

执行后的SQL语句:

1  select
2         family0_.id as id0_,
3         family0_.username as username0_,
4         family0_.address as address0_,
5         family0_.cost as cost0_ 
6     from
7         family family0_ 
8     where
9         family0_.cost>?

第9行的判断where字句是过滤器附加上去的。

 

Session接口中与Filter对象有关的方法:

方法名

解释

public Filter enableFilter(String filterName)

激活某个过滤器的使用

public Filter getEnableFilter(String filterName)

获取某个激活的过滤器

public void disableFilter(String filterName)

停止某个过滤器的使用

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Hibernate)