In this tutorials, we are going to see how to use filters in hibernate application. Hibernate Filter is used to filter the data.

Filtering the data means, getting the information from database based on certain conditions. Usually, we will do this, by using the conditional queries. That  means writing queries using where clause. So that we can get the data with respect to the condition.

Instead of constructing a query with the condition, hibernate has given a solution in the form of filters mechanism.

In hibernate filter mechanism, conditions are filtered as a filter in hbm.xml file and before executing the query in an application a condition can be added to the query or removed from the query. The adding and removing the filter, with the help of either enable or disable a filter.

Here is the complete example for Hibernate Filter :

Hibernate Filter Example  :

Creating Pojo class :

Student.java

[java]

package com.otp.hibernate.pojo;

public class Student {
    private int studentId;
    private String studentName;
    private String address;
    private int age;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    
}

[/java]

Creating hbm.xml

student.hbm.xml

[xml]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.otp.hibernate.pojo.Student" table="student"
        schema="onlinetutorialspoint">
        <id name="studentId" column="id">
            <generator class="increment" />
        </id>
        <property name="studentName" column="name" />
        <property name="address" column="address" />
        <property name="age" column="age" />
        <filter name="studentName" condition="name like ‘%c%’"></filter>
        <filter name="ageFilter" condition="age >= :age"></filter>
    </class>
    <filter-def name="studentName"/>
    <filter-def name="ageFilter">
    <filter-param name="age" type="int"/>
    </filter-def>
</hibernate-mapping>

[/xml]

To define a filter, Hibernate given <filter-def /> tag. If we want, we can pass the parameters to the filter.

[xml]

<filter name="studentName" condition="name like ‘%c%’"></filter>

<filter-def name="studentName"/>

[/xml]

Above is the simple Hibernate Filter for filtering the student names which are starting with ‘c’ character.

Passing the parameters to Filter, through filter-def

[xml]

<filter name="ageFilter" condition="age >= :age"></filter>

<filter-def name="ageFilter">
<filter-param name="age" type="int"/>
</filter-def>

[/xml]

Above is the Hibernate Filter for filtering the students by student’s age. Here the age is passed dynamically, so that we took the age in <filter> as a named parameter (:age)

Lets run the Application :

Before going to execute the application, I am assuming the data in student table like below.

Hibernate Filter Example DATA-minCreate Client Class :

Main.java

[java]

import java.util.Iterator;
import java.util.List;

import org.hibernate.Filter;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.otp.hibernate.pojo.Student;

public class Main {

    public static void main(String[] args) {
        Configuration configuration = new Configuration()
                .configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory factory = configuration.buildSessionFactory(builder
                .build());

        Session session = factory.openSession();
        System.out.println("Student Name Filter");
        System.out.println("——————-");
        
        // enabling the studentName filter
        session.enableFilter("studentName");
        Query query = session.createQuery("from Student s");
        List list = query.list();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Student student = (Student) it.next();
            System.out.println("Student Names which starting with ‘c’ : " + student.getStudentName());

        }
        
        // disabling the studentName filter after the operation
        session.disableFilter("studentName");
        System.out.println("Age Filter");
        System.out.println("——————-");
        // enabling the age filter
        Filter filter = session.enableFilter("ageFilter");
        filter.setParameter("age", 20);

        Query query2 = session.createQuery("from Student s");
        List list2 = query2.list();
        Iterator it2 = list2.iterator();
        while (it2.hasNext()) {
            Student student = (Student) it2.next();
            System.out.println("studentNames who are age >= 20 : " + student.getStudentName());

        }
        
        // disabling the age filter after the operation

        session.disableFilter("ageFilter");
        
        session.clear();
        session.close();
    }

}

[/java]

Output :

Student Name Filter
-------------------
Student Names which starting with 'c' : Chandra
Student Names which starting with 'c' : Chaitanya
Age Filter
-------------------
studentNames who are age >= 20 : Chandra
studentNames who are age >= 20 : Chaitanya
studentNames who are age >= 20 : Mahesh

 

Happy Learning 🙂

Download Example