0
Sponsored Links


Ad by Google
In our previous post we have seen the example of Hibernate data filter using annotation here we are going to see the implementation Hibernate data filter using hbm.xml.

Data filter enables you to filter data based on some condition although filtering of data can be done using query with where clause or criteria query also, but filter can be easy to manage and filter is enable/disable at any point of your application with minimum effort.

By default filters are not enabled for a given session. Filter is an interface and available inside org.hibernate.Filter package.

How to define filter in hbm.xml

<filter-def name="movieFilter">
<filter-param name="yearParam" type="java.lang.String" />
</filter-def>

How to enable filter:

Filter filter = session.enableFilter("filterName");
filter.setParameter("filterParam", filterValue);

How to disable filter:

session.disableFilter("filterName");

In this project we are going to filter the movies by there released year. Here is ER diagram of table we are using for this project.

Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.3.7
  • MySql 5.1.10
  • Eclipse Juno 4.2
  • Maven 3.2

Main Objects of this project are:
  • pom.xml
  • hibernate.cfg.xml
  • Movie.hbm.xml
  • database

Overview of the Project Structure:















Create database script.

CREATE DATABASE /*!32312 IF NOT EXISTS*/`hibernate_tutorial` ;

USE `hibernate_tutorial`;

/*Table structure for table `movie` */

DROP TABLE IF EXISTS `movie`;

CREATE TABLE `movie` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `released_in_year` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;

Create Movie.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 package="com.javamakeuse.datafilter"> 
	<class name="Movie" table="movie">
		<id name="id" type="java.lang.Long" column="id">
			<generator class="identity" />
		</id>
		<property name="name" type="string" column="name"/>
		<property name="year" type="string" column="released_in_year"/>

		 <filter name="movieFilter" condition="released_in_year = :yearParam"/>
	</class>

	<filter-def name="movieFilter">
		<filter-param name="yearParam" type="java.lang.String" />
	</filter-def>

</hibernate-mapping>

Create 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://localhost:3306/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
  		<property name="hbm2ddl.auto">update</property>
        <mapping resource="Movie.hbm.xml"/>
          
    </session-factory>
</hibernate-configuration>

Create Movie.java pojo class

package com.javamakeuse.datafilter;

public class Movie {

	private long id;

	private String name;

	private String year;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	@Override
	public String toString() {
		return "Movie [id=" + id + ", name=" + name + ", year=" + year + "]";
	}

}


Create MovieMain.java class to enable filter and set filter parameter.

package com.javamakeuse.datafilter;

import java.util.List;

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

public class MovieMain {
 public static void main(String[] args) {
  Session session = buildSessionFactory().openSession();

  session.beginTransaction();

  Filter filter = session.enableFilter("movieFilter");
  filter.setParameter("yearFilter", "2014");

  Query query = session.createQuery("from Movie");
  List<Movie> movieList = query.list();

  for (Movie movie : movieList) {
   System.out.println(movie);
  }

  session.getTransaction().commit();
 }

 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();

  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);
  return sessionFactory;
 }
}

Run MovieMain.java class, It will fetch all the movies whose releasing year is 2014.

OUT PUT:
Movie [id=1, name=Birdman, year=2014]
Movie [id=2, name=Captain America, year=2014]
Movie [id=3, name=Selma, year=2014]
Movie [id=4, name=Boyhood, year=2014]
Movie [id=5, name=Fury, year=2014]

Now disabled the filter using below statement in your MovieMain.java

session.disableFilter("movieFilter");

Run the MovieMain.java after disabling the filter and see the output it will fetch all the movies from the database.

OUT PUT:
Movie [id=1, name=Birdman, year=2014]
Movie [id=2, name=Captain America, year=2014]
Movie [id=3, name=Selma, year=2014]
Movie [id=4, name=Boyhood, year=2014]
Movie [id=5, name=Fury, year=2014]
Movie [id=6, name=Iron Man 3, year=2013]
Movie [id=7, name=Frozen, year=2013]
Movie [id=8, name=Gravity, year=2013]
Movie [id=9, name=Rush, year=2013]
Movie [id=10, name=Argo, year=2012]
Movie [id=11, name=Skyfall, year=2012]

You can see my previous post to create step by step maven project.

Done :)

Download the complete example from here Source Code

Difference between save and persist method

References
Reference 1
Reference 2
Reference 3
Sponsored Links

0 comments:

Post a Comment