Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Hibernate Data Filter Example (XML And Annotation)

In this tutorial we are going to see how can you declare and use Hibernate Data Filters. Filters are a very useful feature in Hibernate, that enables to filter your  received data from the database according to a custom condition. Filters have a unique name for identification and can accept parameters and can also be used with XML mapping and Annotation mapping, as we are going to demonstrate.

So these are the tools we are going to use on a Windows 7 platform:

  • JDK 1.7
  • Maven 3.0.5
  • Hibernate 4.2.3.Final
  • MySQL JDBC driver 5.1.9
  • Eclipse 4.3 Kepler

The basis of this tutorials is going to be this Eclipse project: HibernateMySQLExample.zip. And it’s based in Hibernate 3 with Maven 2 and MySQL 5 Example (XML Mapping and Annotation).

1. Hibernate Data Filter using XML mapping

Remember that the structure of the the project we are going to use is this:

project_struvture

Declare the filter

Open Student.hbm.xml file and paste the following code:

Student.hbm.xml:

<?xml version="1.0"?>
<!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.javacodegeeks.Student" table="student" catalog="tutorials">
		<id name="studentId" type="java.lang.Integer">
			<column name="STUDENT_ID" />
			<generator class="identity" />
		</id>
		<property name="studentName" type="string">
			<column name="STUDENT_NAME" length="10" not-null="true"
				unique="true" />
		</property>
		<property name="studentAge" type="string">
			<column name="STUDENT_Age" length="20" not-null="true" unique="true" />
		</property>

		 <filter name="studentFilter" condition="STUDENT_ID >= :studentFilterID"/>
	</class>

	<filter-def name="studentFilter">
		<filter-param name="studentFilterID" type="java.lang.Integer" />
	</filter-def>

</hibernate-mapping>

Enable the filter

Open App.java file and paste the following code:

App.java:

package com.javacodegeeks;

import java.util.List;

import org.hibernate.Filter;
import org.hibernate.Query;
import org.hibernate.Session;

import com.javacodegeeks.utils.HibernateUtil;

public class App {
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		session.beginTransaction();

		Filter filter = session.enableFilter("studentFilter");
		filter.setParameter("studentFilterID", 49);

		Query query = session.createQuery("from Student");

		List<?> list = query.list();

		for (int i = 0; i < list.size(); i++) {

			Student student = (Student) list.get(i);
			System.out.println(student);
		}

		session.getTransaction().commit();

	}
}

Output:

Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_, student0_.STUDENT_Age as STUDENT3_0_ from tutorials.student student0_ where student0_.STUDENT_ID >= ?
Student [studentId=49, studentName=JavaFun, studentAge=19]
Student [studentId=50, studentName=JavaFun, studentAge=19]
Student [studentId=51, studentName=JavaFun, studentAge=19]
Student [studentId=52, studentName=JavaFun, studentAge=19]
Student [studentId=53, studentName=JavaFun, studentAge=19]
Student [studentId=54, studentName=JavaFun, studentAge=19]
Student [studentId=55, studentName=JavaFun, studentAge=19]

Now if you comment lines 17,18 of the above code to disable the filter and run the program again these are the results:

Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_, student0_.STUDENT_Age as STUDENT3_0_ from tutorials.student student0_
Student [studentId=4, studentName=JavaFun, studentAge=19]
Student [studentId=5, studentName=JavaFun, studentAge=19]
Student [studentId=6, studentName=JavaFun, studentAge=19]
Student [studentId=8, studentName=James, studentAge=19]
Student [studentId=9, studentName=Akilis, studentAge=19]
Student [studentId=10, studentName=Akilis, studentAge=19]
Student [studentId=11, studentName=Jeremy, studentAge=45]
Student [studentId=12, studentName=Jeremy, studentAge=45]
Student [studentId=31, studentName=Jeremny, studentAge=21]
Student [studentId=32, studentName=JavaFun, studentAge=19]
Student [studentId=33, studentName=JavaFun, studentAge=19]
Student [studentId=34, studentName=JavaFun, studentAge=19]
Student [studentId=35, studentName=JavaFun, studentAge=19]
Student [studentId=36, studentName=JavaFun, studentAge=19]
Student [studentId=37, studentName=JavaFun, studentAge=19]
Student [studentId=38, studentName=JavaFun, studentAge=19]
Student [studentId=40, studentName=Jeremy, studentAge=21]
Student [studentId=46, studentName=JavaFun, studentAge=19]
Student [studentId=47, studentName=JavaFun, studentAge=19]
Student [studentId=48, studentName=JavaFun, studentAge=19]
Student [studentId=49, studentName=JavaFun, studentAge=19]
Student [studentId=50, studentName=JavaFun, studentAge=19]
Student [studentId=51, studentName=JavaFun, studentAge=19]
Student [studentId=52, studentName=JavaFun, studentAge=19]
Student [studentId=53, studentName=JavaFun, studentAge=19]
Student [studentId=54, studentName=JavaFun, studentAge=19]
Student [studentId=55, studentName=JavaFun, studentAge=19]

So you can see that the filter us working well. To disable the filter dynamically in your application you can simply use :

...
   session.disableFilter("studentFilter");
...

Now, the filter will be disabled and your queries will return unfiltered results.

1. Hibernate Data Filter using Annotations

For this we are going to use the Eclipse project of  Hibernate 3 with Maven 2 and MySQL 5 Example (XML Mapping and Annotation) that deals with Annotations. It’s right here : HibernateMySQLAnnot.zip.

Here is how to define a filter in Student.java file:

Student.java:

package com.javacodegeeks;

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;

@Entity
@FilterDef(name = "studentFilter", parameters = @ParamDef(name = "studentFilterID", type = "java.lang.Integer"))
@Table(name = "student", catalog = "tutorials")
@Filter(name = "studentFilter", condition = "STUDENT_ID > :studentFilterID")
public class Student implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private Integer studentId;
	private String studentName;
	private String studentAge;

	public Student() {
	}

	public Student(String studentName, String studentAge) {
		this.studentName = studentName;
		this.studentAge = studentAge;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "STUDENT_ID", unique = true, nullable = false)
	public Integer getStudentId() {
		return this.studentId;
	}

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

	@Column(name = "STUDENT_NAME", nullable = false, length = 10)
	public String getStudentName() {
		return this.studentName;
	}

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

	@Column(name = "STUDENT_AGE", nullable = false, length = 20)
	public String getStudentAge() {
		return this.studentAge;
	}

	public void setStudentAge(String studentAge) {
		this.studentAge = studentAge;
	}

	@Override
	public String toString() {
		return "Student [studentId=" + studentId + ", studentName="
				+ studentName + ", studentAge=" + studentAge + "]";
	}

}

Now using the same App.java as above these are the results:
Output:

Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.STUDENT_NAME as STUDENT2_0_, student0_.STUDENT_Age as STUDENT3_0_ from tutorials.student student0_ where student0_.STUDENT_ID >= ?
Student [studentId=49, studentName=JavaFun, studentAge=19]
Student [studentId=50, studentName=JavaFun, studentAge=19]
Student [studentId=51, studentName=JavaFun, studentAge=19]
Student [studentId=52, studentName=JavaFun, studentAge=19]
Student [studentId=53, studentName=JavaFun, studentAge=19]
Student [studentId=54, studentName=JavaFun, studentAge=19]
Student [studentId=55, studentName=JavaFun, studentAge=19]

Reading the Jboss documentations is always useful. This was an example on how to use Hibernate Data Filters using both XML mapping and Annotation.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close