RSS

Hibernate过滤器

10 Apr

Hibernate过滤器的概念

1. Hibernate的过滤器类似Servlet的过滤器,多获取的数据进行过滤处理

2. Hibernate的过滤器的过滤条件,需要配置在映射文件中

3. 通过调用Session对象的setFilter()和enableFilter()方法是用过滤器

 

使用<filter-def>标签定义过滤器

<hibernate-mapping>

<class name="hibernate.example.vo.GuestBook" table="GUESTBOOK">

</class>

<filter-def name="nameFilter">

<filter-param name="inputName" type="java.lang.String"/>

</filter-def>

</hibernate-mapping>
使用<filter>标签声明使用过滤器
<hibernate-mapping>
              <class name="hibernate.example.vo.GuestBook" table="GUESTBOOK">
                            <filter name="nameFilter" condition="NAME=:inputName"/>
              </class>
</
hibernate-mapping>
表示使用该过滤器查找GUESTBOOK表中NAME的值为输入参数的值

 

调用Hibernate过滤器的例子

String hql = "from GuestBook where id between 10 and 200";

Transaction tx = session.beginTransaction();

Query query = session.createQuery(hql);

Filter filter = session.enableFilter("nameFilter");

filter.setParameter("inputName", "Xavier");

List<GuestBook> list = query.list();

tx.commit();

 

使用<filter>标签声明使用过滤器(集合当中的对象)

<class name="hibernate.example.vo.Category" table="CATEGORY">

<set name="products" cascade="save-update" inverse="true">

<key column="category_id"/>

<one-to-many class="hibernate.example.vo.Product"/>

<filter name="priceFilter" condition="PRICE>:inputPrice"/>

</set>

</class>

<filter-def name="priceFilter">

<filter-param name="inputPrice" type="java.lang.Double"/>

</filter-def>

session.beginTransaction();

String hql = "select c from Category c inner join fetch c.products where c.id < 100 order by c.id < 100 order by c.id desc";

Query query = session.createQuery(hql);

Filter filter = session.enableFilter("priceFilter");

filter.setParameter("inputPrice", 30.0);

session.getTransaction().commit();

for(Category c: list){

Set<Product> set = c.getProducts();

for(Product p:set){

System.out.println(p.getName() + " – " + p.getPrice());

}

}

Advertisements
 
Leave a comment

Posted by on 04/10/2011 in HIBERNATE

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: