1
Sponsored Links


Ad by Google
In our previous post we have seen the example of inheritance mapping in hibernate here we are going to see the implementation of one of the hidden feature of hibernate called data filter using annotation.
Data filter enables you to filter data based on some condition although filtering of data can be done with 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 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
  • annotated pojo
  • 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 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 class="com.javamakeuse.datafilter.Movie"/>
          
    </session-factory>
</hibernate-configuration>

Create Movie.java entity: See here we have defined the name of filter as movieFilter and parameter of filter as yearFilter @FilterDef and @ParamDef are used.

package com.javamakeuse.datafilter;

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

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

@Entity
@Table(name = "movie")
@FilterDef(name = "movieFilter", parameters = @ParamDef(name = "yearFilter", type = "java.lang.String"))
@Filter(name = "movieFilter", condition = "released_in_year = :yearFilter")
public class Movie {

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private long id;

 @Column(name = "name")
 private String name;

 @Column(name = "released_in_year")
 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

References
Reference 1
Reference 2

Sponsored Links

1 comments:

  1. How does one solve this:
    org.hibernate.HibernateException: No such filter configured [createdFilter]

    ReplyDelete