Hibernate data filter example – XML and annotation

Hibernate data filter is an innovative way to filter the retrieve data from database, in a more reusable way and “visibility” rules. The data filter has a unique name, global access and accept parametrized value for the filter rule, you can enable and disabled it in a Hibernate session.

Hibernate data filter example

In this example, it defined a data filter and filter the collection data with specified date. The Hibernate data filter can be implemented both in XML mapping file and annotation.

1. Hibernate data filter in XML mapping file

Define a data filter with ‘filter-def‘ keyword, and accept a date parameter.

<filter-def name="stockRecordFilter">
     <filter-param name="stockRecordFilterParam" type="date"/>
XML mapping example

A XML mapping file example to declare and assign it to collection set.

 <class name="com.mkyong.common.Stock" table="stock" catalog="mkyong">
   <set name="stockDailyRecords" inverse="true" table="stock_daily_record">
         <column name="STOCK_ID" not-null="true" />
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
    <filter name="stockRecordFilter" condition="date >= :stockRecordFilterParam"/>
 <filter-def name="stockRecordFilter">
   <filter-param name="stockRecordFilterParam" type="date"/>

In condition=”date >= :stockRecordFilterParam”, the ‘date’ is a properties belong to ‘StockDailyRecord’.

2. Hibernate data filter in annotation

Define a data filter with ‘@FilterDef‘ keyword, and accept a date parameter with @ParamDef.

parameters=@ParamDef( name="stockRecordFilterParam", type="date" ) )
Annotation example

An annotation file example to declare and assign it to collection set.

parameters=@ParamDef( name="stockRecordFilterParam", type="date" ) )
@Table(name = "stock", catalog = "mkyong")
public class Stock implements java.io.Serializable {
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
		name = "stockRecordFilter",
		condition="date >= :stockRecordFilterParam"
	public Set<StockDailyRecord> getStockDailyRecords() {
		return this.stockDailyRecords;

In condition=”date >= :stockRecordFilterParam”, the ‘date’ is a properties belong to ‘StockDailyRecord’.

How to enable and disable data filter

Enable the data filter.

Filter filter = session.enableFilter("stockRecordFilter");
filter.setParameter("stockRecordFilterParam", new Date());

Disable the data filter.


Applying and implementing the date filter

Here’s a code snippet to show how to applying and implementing the data filter.

        Session session = HibernateUtil.getSessionFactory().openSession();
        System.out.println("****** Enabled Filter ******");
        Filter filter = session.enableFilter("stockRecordFilter");
        filter.setParameter("stockRecordFilterParam", new Date());
        Stock stock = (Stock)session.get(Stock.class, 2);
        Set<StockDailyRecord> sets = stock.getStockDailyRecords();
        for(StockDailyRecord sdr : sets){
        System.out.println("****** Disabled Filter ******");
        //clear the loaded instance and get Stock again, for demo only
        Stock stock2 = (Stock)session.get(Stock.class, 2);
        Set<StockDailyRecord> sets2 = stock2.getStockDailyRecords();
        for(StockDailyRecord sdr : sets2){


****** Enabled Filter ******
****** Disabled Filter ******

In this example (both XML and annotation), after the filter is enabled, all its ‘StockDailyRecord’ collection is filter by your parameter date.

P.S filter.setParameter(“stockRecordFilterParam”, new Date());, the current new Date is 2010-01-27.

Tags :

About the Author

Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


  • Pingback: plan()

  • Pingback: house blue()

  • Pingback: plumber auger()

  • Pingback: locksmith union city()

  • Pingback: ave x locksmith()

  • Pingback: electrician 2391 jobs()

  • Pingback: 24/7 electrician perth()

  • Pingback: paypal loans()

  • Pingback: stop parking()

  • Pingback: water ionizer pay plan loans()

  • Pingback: pay day loans()

  • Pingback: YouTube likes kopen()

  • Pingback: water ionizer()

  • Pingback: laan penge online nu()

  • Pingback: parking()

  • Pingback: mp4 mobile porn()

  • Pingback: tv packages()

  • Pingback: DIRECTV()

  • Pingback: Blue Coaster33()

  • http://[email protected] fernando ferrandini


    i’m having the same problem with JPA2. the hibernate query doesnt change at all. Could you manage to do it?

  • Doahh

    Extremely helpful thanks.

    I haven’t really tested it but it seems to require the:

    session.get(MyEntity.class , id)

    and didn’t seem to work with a:

    session.createQuery(&quot;SELECT MyEntity myEntity WHERE myEntity.id = :id&quot;)

    which if I am correct is quite annoying as it means there are many ways to do something but only one works.

  • Priyank Doshi

    Here StockDailyRecords is LAZY. So when you fire stock.getStockDailyRecords(), will hibernate fire another DB query in back ground to retrive all records of StockDaily and then apply filter?

  • Susil Kumar Rout

    I read the tutorial but I couldn’t understand that what is the benifit of hibernate Filters
    over “where” clause.Please guide me

  • erramun

    Hi! Nice example but… what if the collection to be filtered is lazy loaded and you want to apply the filter to it? I mean… supose you enable de filter when retrieving the data and you disable it after that. Then, when you lazy load the collection would it be affected by the filter?

  • steave


    Your article is very nice. I created small example based on your article.
    It is working fine with XML but i am not success with annotations. It is giving the error
    No such filter configured [statusFilter]
    Can you check my code pls

    @FilterDef(name=”statusFilter”,parameters=@ParamDef( name=”statusParam”, type=”string” ))
    @Filter(name=”statusFilter”, condition=”status=:statusParam”)
    public class Flight
    private int id;
    private String flightNo;
    private String source;
    private String destination;
    private String status;

    public int getId()
    return id;
    private void setId(int id)
    this.id = id;

    public String getFlightNo()
    return flightNo;
    public void setFlightNo(String flightNo)
    this.flightNo = flightNo;
    public String getSource()
    return source;
    public void setSource(String soruce)
    this.source = soruce;
    public String getDestination()
    return destination;
    public void setDestination(String destination)
    this.destination = destination;
    public String getStatus()
    return status;
    public void setStatus(String status)
    this.status = status;

  • Amit

    I am trying to do the same using jpatemplate but I am not able to apply filter. When I see the query generated it does not include the filter that I have applied using @Filter. Please help.

  • Pingback: Hibernate Tutorials | Tutorials()