Tech I Enjoy Logo

Custom Search




  Home >> Hibernate


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.

Software environment that I have used in this example are as follows:
1. Eclipse 3.2
2. JDK 1.5
3. Hibernate 3.2

And I tried to see ways of using two ways of putting where condition to
any SQL that is ultimately executed at database side.

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.techienjoy.com/Hibernate-One-to-Many-mapping-example.php 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. Client.java
    
    /**
    *  This source is provided as is, without any warranty
    *  and /or guaranty of any kind.
    *  Copyright (C) 2008, TECHIENJOY.COM, 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. If you like to share your comment/suggestions/feedback relating to this Page, you can do so by droping us an email at usingframeworks @ gmail . com with the subject line mentioning URL for this Page (i.e, /Hibernate-criteria-filter-example.php) or use this LINK. As per this website's privacy policy, we never disclose your email id, though we shall post your comments/suggestions/feedback with your name (optional) and date on this Page. If you don't want your comments/suggestions/feedback to be shared in this Page, please mention so in your email to us. Thank you very much..... If anything missed out , please let me know at techienjoy at yahoo . com
    Hibernate Property Formula :
    Hibernate Example on Property
    Tag with ease to do code walk-through
    Hibernate Example on composite Primary key :
    Example on using Hibernate Framework
    to work with mapping using composite
    Primary key.
    Hibernate Many to Many Mapping Example :
    Many to many mapping example using Hibernate
    Framework and a simple to follow steps.
    Hibernate Interview Questions :
    Interview Questions on Hibernate with answer.
    Hibernate Example on Filter :
    Example on using Filter using Hibernate Framework
    to work with.
    Hibernate Example on Filter Criteria :
    Example on using Filter Criteria
    using Hibernate Framework to work with.
    Hibernate Transaction on JBoss :
    Explaining Transaction using Hibernate
    on JBoss Application Server.
    List of Examples on Hibernate :
    List of example using Hibernate.
    Hibernate Named Query Example :
    Named Query markup using an example
    and Hibernate Framework.
    Hibernate one to many mapping Example :
    one to many mapping explained using an example
    and Hibernate Framework.
    Hibernate Join Example :
    Using Table join explained with an example
    while using Hibernate Framework.
    Class Hierarchy Mapping Example :
    class hierarchy mapping example using Hibernate
    Framework and a simple to follow steps.
    Hibernate Component Property :
    Hibernate Example on Component 
    with source code explained.
    Hibernate Bag Mapping Example :
    class mapping using Bag Tag example using Hibernate
    Framework and a simple to follow steps.
    Hibernate class heirarchy mapping :
    Hibernate Example on mapping
    class hierarchy using various ways
    of persisting into database
    tables.
    Hibernate Insert Update control :
    Hibernate Example on controlling
    insert and update attributes
    Hibernate one to one mapping Example :
    one to one mapping explained using an example
    and Hibernate Framework.
    Example on persisting Class Hierarchy :
    Example on using Hibernate Framework
    to persist Class Hierarchy into database.
    Hibernate one to many mapping Example :
    one to many mapping explained using an example
    and Hibernate Framework.
    Hibernate Interceptor Example :
    Example on using Interceptor using Hibernate Framework
    with source code explained.


    References :
    Tags: Hibernate Class Hierarchy Persist example
    Tags: Hibernate composite primary key
    Tags: Hibernate criteria filter example
    Tags: Hibernate Filter Example
    Tags: Hibernate Interceptor example
    Tags: Hibernate Interview Questions
    Tags: Hibernate join example
    Tags: Hibernate Many to Many Mapping Example
    Tags: Hibernate mapping bag
    Tags: Hibernate mapping class hierarchy table per subclass
    Tags: Hibernate named query markup
    Tags: Hibernate One to Many mapping example
    Tags: Hibernate One To One Mapping Example
    Tags: Hibernate scenario one to many
    Tags: Hibernate transaction jboss
    Tags: Hibernate
    

    
    
    DISCLAIMER :
    The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
    techienjoy.com is not liable for any negative consequences that may result/arise from 
    implementing directly/indirectly any information covered in these pages/articles/tutorials.
    
    All contents of this site is/are written and provided on an "AS IS" basis,
    without WARRANTIES or conditions of any kind, either express or implied, including, without
    limitation, merchantability, or fitness for a particular purpose. You are solely responsible
    for determining the appropriateness of using or refering this and assume any risks associated
    with this.
    
    In spite of all precautions taken to avoid any typo in these pages, there might be some 
    issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
    extends sincerest apologies to all our visitors for the same.
    
    
    

    Android Examples || Android Examples

    © Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions