Advertisement
Home > Hibernate Tutorial > Hibernate Filter Example > Hibernate Criteria ExamplePlease log in to add or reply to any matter<- requires login or
RMI Example

Home > Hibernate Tutorial > Hibernate Filter Example > Hibernate Criteria Example
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Interview Questions
Description : On Hibernate
More...


Written By : Amit
Title :
mapping class hierarchy table per subclass
Description : Example
More...


Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...

Hibernate Criteria, Hibernate Filter, Hibernate, Example, Code, Tutorial, Article
Author : ISHTEK
Date (Year/Month/Date): 2009-06-08 Hibernate Criteria and Hibernate Filter Example Explained :
Hibernate Query and Hibernate Criteria demo with example code
By just extending an example that was already on display in this site,
I just tried to add some Hibernate Filter and Hibernate Criteria 
features provided by Hibernate Framework.

My Software environment for this example:
1. Eclipse 3.2
2. JDK 1.5
3. Hibernate 3.2

And I tried to see ways of using both or one of these two ways of
putting where condition to any SQL that is ultimately executed at
database level.

In order to use Hibernate Filter functionality, one has to define
the Filter in HBM descriptor XML file, within <filter-def> Tag.
This Filter-def tag can be defined at the class Tag level or within the
dependent or related SET/BAG collection tag (in case of one to many
type of mapping). So the existing DeptsEmployee.HBM.XML file will 
be having entries for Filter-Def, Filter-Param and Filter Tags, as 
follows:

DeptsEmployee.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="demo">
  <class name="Dept" table="dept">
    <id name="deptId" column="dept_id">
      <generator class="assigned"/>
    </id>
    <property name="deptName" column="dept_name" type="java.lang.String"/>
    <set name="employees" table="employee" cascade="persist,delete">
      <key column="dept_id" />
      <one-to-many class="Employee"/>
    </set>
  </class>
  <class name="Employee" table="employee">
    <id name="employeeId" column="employee_id">
      <generator class="assigned"/>
    </id>
    <property name="employeeName" column="employee_name" type="java.lang.String"/>
    <one-to-one name="dept" class="Dept" />
    <filter name="listStartsWithCapitalT" condition="employee_name like :employeeName1"/>
  </class>
  <filter-def name="listStartsWithCapitalT">
	  <filter-param name="employeeName1" type="string"/>
  </filter-def>

</hibernate-mapping>
Remaining files of this example can be used from the following link, http://www.interview-questions-tips-forum.net/index.php/Hibernate-Tutorial/One-to-Many-mapping-example/Code as I have just used files from that Page for rapidly setting up environment for one to Many Hibernate mapping example with Hibernate Filter and Hibernate Criteria and Hibernate Query. List of files includes:
  • Dept.java
  • Employee.java
  • hibernate.cfg.xml
  • As the above HBM XML file shows, filter-def has a filter-param with a name and type attribute. This filter-def name attribute will be used in filter Tag in the class or set tags etc. Tag filter-param name attribute will be used with a ":" prefix, as the place holder in the where criteria expression, whose value is to be passed from the Client code. <filter name="listStartsWithCapitalT" condition="employee_name like :employeeName1"/> Now we can go through the Client code, showing ways to use Hibernate Filter with Hibernate criteria. Before using any Hibernate Filter, it has to be enabled for the Hibernate Session that is to be used for executing the Query or Criteria.
    Advertisement
    Client.java
    
    /**
    *  This source is provided as is, without any warranty
    *  and /or guaranty of any kind.
    *  Copyright (C) 2008, ISHTIAK, All Rights Reserved.
    *  You can use it for Personal Learning purpose only.
    *  E-mail: usingframeworks@gmail.com
    */
    package demo;
    
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.criterion.Restrictions;
    
    public class Client {
        // Hibernate SessionFactory
        SessionFactory sessionFactory;
        public Client() {
            //Hibernate Configuration
            Configuration conf = new Configuration();
            //Loading configuration properties file 
    		//and building Hibernate SessionFactory.
            sessionFactory =
    		    conf.configure("hibernate.cfg.xml")
    			    .buildSessionFactory();
            if(sessionFactory != null) {
                Session session = sessionFactory.getCurrentSession();
                Transaction trans = session.getTransaction();
                trans.begin();
                session.enableFilter("listStartsWithCapitalT");
                Criteria criteria = session.createCriteria(Employee.class);
                session.getEnabledFilter("listStartsWithCapitalT")
    			       .setParameter("employeeName1", "%test%");
                criteria.add(Restrictions.like("employeeName", "%test1"));
                List list = criteria.list();
                System.out.println(list.size());
                trans.commit();         
            }
            
        }
    	
        /**
         * Client main method
         * @param args
         */
        public static void main(String[] args) {
            new Client(); 
        }
    
    }
    
    
    As shown in the above Client code, we have used both Filter and Hibernate Criteria with Restrictions to add another filter criteria So following is the final SQL that is getting printed in screen output / console as
    (Auto generated by Hibernate, just for reference)
    select this_.employee_id as employee1_1_1_, this_.employee_name as
    employee2_1_1_, dept2_.dept_id as dept1_0_0_, dept2_.dept_name as dept2_0_0_
    from employee this_ left outer join dept dept2_ on
    this_.employee_id=dept2_.dept_id where this_.employee_name like ? and
    this_.employee_name like ?
    
    As the section in bold (above) shows that we have enabled the filter criteria as defined in HBM file, as well as the Client code using Hibernate Restrictions feature to add LIKE function for the employee name like filter criteria.
    Advertisement
    Author of this article/writeup has expressed his/her willingness
    to help or guide users with any technical difficulties he/she faces while working with the example code environment setting up, running and resolving any such exception raised during compile or at runtime. You may ask for any technical doubt or seek technical help related to this article by using following form to reach for technical help from the Author for FREE. This article's Author shall be reading your request and responding within reasonable time (no resolution timeframe defined as such).
     
    Replied By ->
    Amit
    Can you provide a sample example on using Outer Join fetch
    , using Hibernate Filter??
    
    For example, select on all employees whose salary is greater
    than some amount and employee's department is having listed in 
    some special benifit or allowance criterias...
    
    So we have here Employee table and Allowance_Criteria and 
    Department tables.
    
    Employee table has a department_id column and Allowance_criteria table has also department_id column,
    where
    department_id are foreign key to the Department table(department_id primary key).
    
    so while selecting for employees records for some particular
    salary, one has to join department_id in employee and 
    Allowance_criteria tables as well..
    
    Can you please help to comeup with some example code on this
    example requirement??
    
    Thanks in advance.
    
    
     
     

    Commented By ->
    ISHTEK
    There is an example on Hibernate Filter by using session.createFilter 
    API, that I have added recently at
    
    http://www.interview-questions-tips-forum.net/index.php/Hibernate-Tutorial/Hibernate-Filter/Hibernate-Filter-Example
    
    Please write your comments on this example and to improve my tech 
    writing skill.
    Please write your Comment on this Matter
    (This will be visible if found suitable):
    Name: *
    Email (will not be displayed): *
    Matter: *
    13,33
    Enter bigger number from above :*
    Home > Hibernate Tutorial > Hibernate Filter Example > Hibernate Criteria Example
    Visitor/User submitted related resources:
    (Visible upon review and approved by this site Administrator)
    
    Referred By Name *:
    Resource URL *: (e.g, URL should be starting with http://www.-----.---)
     
    Resource Short Description *:
    33,40
    Enter bigger number from above : *

    Please log in to add or reply to any matter<- requires login
    Log in or Register
    This List is generated as on 2009-07-12 (YYYY-MM-DD)
    #Discuss-these : questions-and-answer : Interview-Questions-on-Java
    #Question-on-Session-Factory-Creation : SessionFactory : Hibernate-Tutorial
    #On-Hibernate : Interview-Questions : Hibernate-Tutorial
    #Example : mapping-class-hierarchy-table-per-subclass : Hibernate-Tutorial
    #Example : ways-create-Hibernate-SessionFactory : Hibernate-Tutorial
    #Example : Spring-Hibernate-Integration-example : Hibernate-Tutorial
    #Discussion : ORM-Hibernate-Best-FIT : Hibernate-Tutorial
    #Code : One-to-Many-mapping-example : Hibernate-Tutorial
    #code : Many-to-Many-Mapping-Example : Hibernate-Tutorial
    #discussion : Interview-questions-answer : Hibernate-Tutorial
    #example-code : Interceptor-use-log-SQL-statements : Hibernate-Tutorial
    #code : Class-Hierarchy-Persist-example : Hibernate-Tutorial
    #discussion : Case-study-Hibernate : Hibernate-Tutorial
    #With-Answer : Hibernate-Interview-Questions : Hibernate-Tutorial
    #Discussed : Hibernate-Interview-questions-answer : Hibernate-Tutorial
    #Question : Hibernate-Transaction : Hibernate-Tutorial
    #Example-Case-study : Contextual-Session : Hibernate-Tutorial
    #Design-with-example-code : Struts2-Hibernate : Hibernate-Tutorial
    #Hibernate-query : Hibernate-Criteria : Hibernate-Tutorial
    #Hibernate-Criteria-Example : Hibernate-Filter-Example : Hibernate-Tutorial
    #Hibernate-Filter-Example : Hibernate-Filter : Hibernate-Tutorial
    #Hibernate-Sample : Hibernate-many-to-one : Hibernate-Tutorial
    #Hibernate-Sample-Example : Hibernate-named-query : Hibernate-Tutorial
    #Composite-Primary-Key : Hibernate-Composite-Key : Hibernate-Tutorial
    #Mapping-Example : Hibernate-one-to-one : Hibernate-Tutorial
    Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
    CONTACT    PRIVACY POLICY    DISCLAIMER
    
    This web site provides some of the information about various technologies, example 
    code, tips, tutorials etc. Like any printed matterials, content of these pages may 
    become out of date over a period of time. Therefore all visitor/users of this web 
    site are requested/advised to refer to the originating parties/sources for the 
    latest changes and happenings for detailed information. This information is not 
    intended to be a substitute for the original reference provided by the originating 
    parties/sources.