---
title: "Hibernate 如何使用filter"
author: "lifaming15"
date: "2013-03-10T11:57:00Z"
tags: []
slug: "hibernate-filter"
draft: false
lastmod: "2013-08-28T21:54:42Z"
id: 1932893
url: "https://lifaming15.iteye.com/blog/1932893"
---

@Entity  
@Table(name = "T\_SEN\_DISABILITY\_TYPE")  
在使用filter的时候还需要定义filter参数。 name 为filter名称，parameters为filter参数，@ParamDef为参数定义，其中那么为appOrCase（参数名称） type为该参数类型  
@FilterDef(name = "appOrCaseFilter", parameters = @ParamDef(name = "appOrCase", type = "string"))  
public class DisabilityType extends IdEntity {  
private List&lt;SpecNeedQuestion&gt; specNeedQuestions;

@OneToMany(fetch = FetchType.LAZY)  
@Filters( { @Filter(name = "appOrCaseFilter", condition = ":appOrCase=app\_or\_case") })  
@JoinColumn(name = "DIS\_TYPE\_ID")  
@OrderBy("qstIndex")  
public List&lt;SpecNeedQuestion&gt; getSpecNeedQuestions() {  
return specNeedQuestions;  
}

public void setSpecNeedQuestions(List&lt;SpecNeedQuestion&gt; specNeedQuestions) {  
this.specNeedQuestions = specNeedQuestions;  
}  
@Filters定义该对象关联specNeedQuestion对象是对应的所有的filters。  
@Filter 指定单个的filter 属性：name为filter的名字。Condition为filter的过滤条件，其中：app\_or\_case为SpecNeedQuestion对象对应的表的字段，：appOrCase为参数名称。

public List&lt;DisabilityType&gt; getDisables(String appOrCase) {  
String hql = "from DisabilityType t order by t.type";  
Session session = this.getSession();  
Filter filter = session.enableFilter("appOrCaseFilter");  
filter.setParameter("appOrCase", appOrCase);  
return find(hql);  
}