Home arrow Java arrow Page 4 - Hibernate: Paving the Path for Queries
JAVA

Hibernate: Paving the Path for Queries


In the second part of our series on Hibernate, we will take a close look at its architecture and core classes. We will also cover the different types of queries possible in Hibernate. Finally, we'll use a real world example to illustrate our discussion.

Author Info:
By: A.P.Rajshekhar
Rating: 4 stars4 stars4 stars4 stars4 stars / 14
December 20, 2005
TABLE OF CONTENTS:
  1. · Hibernate: Paving the Path for Queries
  2. · Understanding the Architecture
  3. · Queries: Understanding the Types
  4. · In the Real World: Continued

print this article
SEARCH DEVARTICLES

Hibernate: Paving the Path for Queries - In the Real World: Continued
(Page 4 of 4 )

Following is the code that was fetching the data according to the provided id:

package test;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.someorg.persist.Order;
// use as
// java test. FindOrderById name
public class FindOrderById {
    public static void main(String[] args) throws Exception {
        // query to issue
        String query =
            "select order from Order "
             + "where order.id=:id";
        // search for what?
        String name = args[0];
        // init
        Configuration cfg = new Configuration()
                           .addClass(Order.class);
        SessionFactory sf = cfg.buildSessionFactory();
        // open session
        Session sess = sf.openSession();
       
        // search and return
        List list = sess.find(query, id,
                              Hibernate.STRING);
        if (list.size() == 0) {
            System.out.println("No Order having id "
                               + name);
            System.exit(0);
        }
        Order o = (Order) list.get(0);
        sess.close();
        System.out.println("Found Order: " + p);
    }
}

It is the bolded lines that will be changed. So let's get started.

The following is the above code rewritten using HQL. The bolded lines indicate the changes made.

package test;
import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
    public static void main(String[] args) throws Exception {
        // query to issue
        String query =
            "select order from Order "
             + "where order.id=:id";
        // search for what?
        String name = args[0];
        // init
        Configuration cfg = new Configuration()
                           .addClass(Order.class);
        SessionFactory sf = cfg.buildSessionFactory();
        // open session
        Session sess = sf.openSession();
       
        // search and return
      Query q = session.createQuery("from Order order where”+
                                                          +”order.id=:id");
      q.setString(“id”,name);
       List result = q.list();
        if (list.size() == 0) {
            System.out.println("No Order having id "
                               + name);
            System.exit(0);
        }
        Order o = (Order) list.get(0);
        sess.close();
        System.out.println("Found Order: " + p);
    }
}

Now let's do the same using QBC, which is as follows:

package test;
import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
    public static void main(String[] args) throws Exception {
        // query to issue
        String query =
            "select order from Order "
             + "where order.id=:id";
        // search for what?
        String name = args[0];
        // init
        Configuration cfg = new Configuration()
                           .addClass(Order.class);
        SessionFactory sf = cfg.buildSessionFactory();
        // open session
        Session sess = sf.openSession();
       
        // search and return
      Criteria criteria = session.createCriteria(Order.class);
      criteria.add( Expression.eq("id", name) );
      List result = criteria.list();
        if (list.size() == 0) {
            System.out.println("No Order having id "
                               + name);
            System.exit(0);
        }
        Order o = (Order) list.get(0);
        sess.close();
        System.out.println("Found Order: " + p);
    }
}

The main difference between HQL and QBC is clearly visible from the above codes. The HQL works just like SQL. But when QBC is used, the developer is working in a completely object oriented environment. Below is the code using QBE:

import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
    public static void main(String[] args) throws Exception {
        // query to issue
        String query =
            "select order from Order "
             + "where order.id=:id";
        // search for what?
        String name = args[0];
        // init
        Configuration cfg = new Configuration()
                           .addClass(Order.class);
        SessionFactory sf = cfg.buildSessionFactory();
        // open session
        Session sess = sf.openSession();
       
        // search and return
Order exampleOrder = new Order();
exampleOrder.setDate(new Date(1999,10,12);
Criteria criteria = session.createCriteria(Order.class);
criteria.add( Example.create(exampleOrder) );
List result = criteria.list();
        if (list.size() == 0) {
            System.out.println("No Order having Date "
                               + name);
            System.exit(0);
        }
        Order o = (Order) list.get(0);
        sess.close();
        System.out.println("Found Order: " + p);
    }
}

That ends this discussion of the architecture of Hibernate and the categories of the Queries. Now that the architecture is clear we can move on to more complex topics. In the next part I will discuss the life cycle of a persistent object and associations, as object life cycle becomes very important when working with associations. So, till next time.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials