Hibernate Data Filter using XML

In this section, you will learn to filter data using XML mapping file.

Hibernate Data Filter using XML

Hibernate Data Filter using XML

In this section, you will learn to filter data using XML mapping file.

Using filter, you can filter the fetched data from the database. Using filter, you can predefine the filter condition in XML mapping file with a unique name. And you can use this filter using this unique name.

EXAMPLE

In this example, we will filter the records whose employee_id is greater than 4. We set the filter in Address.hbm.xml using <filter-def> tag. The two tables address and employee has one-to-many relationship as shown below :

The project hierarchy and jar file used is given below :

The SQL query used to create address table is given below :

CREATE TABLE `address` ( 
`address_id` bigint(20) NOT NULL auto_increment, 
`street` varchar(50) default NULL, 
`city` varchar(50) default NULL, 
`state` varchar(50) default NULL, 
`country` varchar(50) default NULL, 
PRIMARY KEY (`address_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

The SQL query used to create employee table is given below :

CREATE TABLE `employee` ( 
`employee_id` bigint(10) NOT NULL auto_increment, 
`firstname` varchar(50) default NULL, 
`lastname` varchar(50) default NULL, 
`cell_phone` varchar(15) default NULL, 
`address_id` bigint(20) default NULL, 
PRIMARY KEY (`employee_id`), 
KEY `FK_employee` (`address_id`), 
CONSTRAINT `FK_employee` FOREIGN KEY (`address_id`) REFERENCES `address` (`address_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1

For inserting records using one-to-many mapping in the above tables click here .(Example).

CODE

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://192.168.10.13:3306/anky</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>

</session-factory>
</hibernate-configuration>

Address.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 package="net.roseindia">
<class name="Address" table="address">
<id name="addressId" column="address_id">
<generator class="native" />
</id>
<property name="street" column="street"/>
<property name="city" column="city"/>
<property name="state" column="state"/>
<property name="country" column="country"/>
<set name="employees" table="employee"
inverse="false" lazy="true" fetch="select">
<key>
<column name="address_id" not-null="true" />
</key>
<one-to-many class="net.roseindia.Employee" />
<filter name="addressFilter" condition="employee_id >= :addressFilterParam"/>
</set>
</class>
<filter-def name="addressFilter">
<filter-param name="addressFilterParam" type="long"/>
</filter-def>
</hibernate-mapping>

Address.java

package net.roseindia;

import java.util.Set;

public class Address {

private Long addressId;

private String street;

private String city;

private String state;

private String country;

private Set<Employee> employees;

public Long getAddressId() {
return addressId;
}

public void setAddressId(Long addressId) {
this.addressId = addressId;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public Set<Employee> getEmployees() {
return employees;
}

public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}

Employee.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 package="net.roseindia">

<class name="Employee" table="employee">
<id name="employeeId" column="employee_id">
<generator class="native" />
</id>

<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname" />
<property name="cellphone" column="cell_phone" />

<many-to-one name="address" class="net.roseindia.Address" fetch="select">
<column name="address_id" not-null="true" />
</many-to-one>

</class>
</hibernate-mapping>

Employee.java

package net.roseindia;

public class Employee {
private Long employeeId;

private String firstname;

private String lastname;

private String cellphone;

private Address address;

public Address getAddress() {
return address;
}

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

public Employee() {}

public Employee(String firstname, String lastname, String phone) {
this.firstname = firstname;
this.lastname = lastname;
this.cellphone = phone;
}

public Long getEmployeeId() {
return employeeId;
}

public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public String getCellphone() {
return cellphone;
}

public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
}

HibernateDataFilterXML.java

package net.roseindia;

import java.util.Date;
import java.util.Set;

import org.hibernate.Filter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateDataFilterXML {
private static SessionFactory sf;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
try {
Configuration configuration = new Configuration().addResource("net/roseindia/Address.hbm.xml").addResource("net/roseindia/Employee.hbm.xml");
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("*****Hibernate Data Filter Using XML*****");
Session session = sf.openSession();
System.out.println("****** Enabled Filter ******");

Filter filter = session.enableFilter("addressFilter");
filter.setParameter("addressFilterParam", new Long(4));

Address address = (Address)session.get(Address.class,new Long(49));
Set<Employee> employee = address.getEmployees();
System.out.println("------------------------------------------------");

for(Employee emp : employee){
System.out.println("Employee ID :"+emp.getEmployeeId());
System.out.println("First Name : "+emp.getFirstname());
System.out.println("Last Name : "+emp.getLastname());
System.out.println("State : "+emp.getAddress().getState());
System.out.println("Country : "+emp.getAddress().getCountry());
System.out.println("------------------------------------------------");
}

System.out.println("****** Disabled Filter ******");

session.disableFilter("stockRecordFilter");
//clear the loaded instance and get Stock again, for demo only
session.evict(address);
session.close();
}
}

OUTPUT

After execution, you will get something like this on console :

*****Hibernate Data Filter Using XML*****
****** Enabled Filter ******
Hibernate: select address0_.address_id as address1_0_0_, address0_.street as street0_0_, address0_.city as city0_0_, address0_.state as state0_0_, address0_.country as country0_0_ from address address0_ where address0_.address_id=?
------------------------------------------------
Hibernate: select employees0_.address_id as address5_0_1_, employees0_.employee_id as employee1_1_, employees0_.employee_id as employee1_1_0_, employees0_.firstname as firstname1_0_, employees0_.lastname as lastname1_0_, employees0_.cell_phone as cell4_1_0_, employees0_.address_id as address5_1_0_ from employee employees0_ where employees0_.employee_id >= ? and employees0_.address_id=?
Employee ID :9
First Name : Suganda
Last Name : Dubey
State : Delhi
Country : India
------------------------------------------------
Employee ID :8
First Name : Rajesh
Last Name : Pandey
State : Delhi
Country : India
------------------------------------------------
****** Disabled Filter ******

Download Source Code