Saturday , April 29 2017
Home / Hibernate / Hibernate Filter Example Xml Configuration

Hibernate Filter Example Xml Configuration

In this tutorials, we are going to implement the filters in hibernate application. Hibernate Filter is used to filter the data. In an application, most of the times we need to filter the data. To filter the data typically we construct the query with where condition. So that we will get the data with respect to the condition.

Instead of constructing the query with 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


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;
    }

    
}

Creating hbm.xml

student.hbm.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>

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


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

<filter-def name="studentName"/>

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


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

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

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


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();
    }

}

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

 

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Hibernate Projection with Example

In this tutorials, we are going to learn about Hibernate Projection with a simple example. …

Leave a Reply

Your email address will not be published. Required fields are marked *