Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials
  

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Hibernate Subqueries

                         

In this section, you will learn about the subqueries with an appropriate example.

Subqueries in hibernate can be referred as the queries that are surrounded by parentheses (). Subqueries solves the purpose of grouping, ordering , narrowing and aggregating the resultant of the query by using the where clause. Notice that the subqueries get executed prior to the main query. The HQL queries may contain the subqueries only in case of if the subqueries are supported by the underline database.

A unidirectional one-to-many association on a foreign key is rarely required.

<?xml version="1.0" encoding="UTF-8"?>

 <!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="net.roseindia.Dealer">
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <bag name="product" inverse="true" cascade="all,delete-orphan">
        <key column="did"/>
        <one-to-many class="net.roseindia.Product"/>
      </bag>

   </class>
</hibernate-mapping>

A unidirectional one-to-many association on a foreign key is rarely required.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
   PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="net.roseindia.Product">
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <property name="did" type="int"/>
      <property name="price" type="double"/>
      <many-to-one name="dealer" class="net.roseindia.Dealer" column="did" 
insert=
"false" update="false"/>

   </class>
 
</hibernate-mapping>

Here is the hibernate code:

In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

package net.roseindia;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Subqueries {

  /**
   @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Session sess = null;
    try{
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String sql_query = "select d.name,p.name,p.price from Product p join p.dealer 
d where p.price in(select p.price from p where p.price > 1500)"
;
      Query query = sess.createQuery(sql_query);
      System.out.println("Dealer Name\t"+"Product Name\t"+"Price");
      for(Iterator it=query.iterate();it.hasNext();){
        Object[] row = (Object[]) it.next();
        System.out.print(row[0]);
        System.out.print("\t\t"+row[1]);
        System.out.print("\t"+row[2]);
        System.out.println();
      }
    sess.close();
    }
    catch(Exception e ){
      System.out.println(e.getMessage());
    }
  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, product0_.price as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id where product0_.price in (select product0_.price from Product product0_ where product0_.price>1500)

Dealer Name    Product Name   Price

Agrawal           Computer          23000.0

Mohan             Mobile              15000.0

Ritu                   HardDisk          2500.0

 

                         

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

1 comments so far (post your own) View All Comments Latest 10 Comments:

The Hibernate documentation says that the subqueries could be used as a column too. I have tried without success, can you post an example of that?

Thanks

Posted by Lean on Tuesday, 01.22.08 @ 22:46pm | #45821

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.