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"/>
</filter-def>
XML mapping example

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

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

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.

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

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

...
@Entity
@FilterDef(name="stockRecordFilter", 
parameters=@ParamDef( name="stockRecordFilterParam", type="date" ) )
@Table(name = "stock", catalog = "mkyong")
public class Stock implements java.io.Serializable {
         ...
	@OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
	@Filter(
		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.

session.disableFilter("stockRecordFilter");

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(sdr.getDailyRecordId());
		System.out.println(sdr.getDate());
	}
 
        System.out.println("****** Disabled Filter ******");
 
        session.disableFilter("stockRecordFilter");
        //clear the loaded instance and get Stock again, for demo only
        session.evict(stock);
 
        Stock stock2 = (Stock)session.get(Stock.class, 2);
        Set<StockDailyRecord> sets2 = stock2.getStockDailyRecords();
 
        for(StockDailyRecord sdr : sets2){
		System.out.println(sdr.getDailyRecordId());
		System.out.println(sdr.getDate());
	}

Output

****** Enabled Filter ******
58
2010-01-31
****** Disabled Filter ******
60
2010-01-02
58
2010-01-31
63
2010-01-23
61
2010-01-03
...

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

mkyong
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.

Comments

  • http://[email protected] fernando ferrandini

    Amit,

    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

    Hi,
    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

    Hi

    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”)
    @Entity
    @Table(name=”FLIGHT_DB”)
    public class Flight
    {
    @Id
    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

    Hi,
    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()