Share on Google+Share on Google+

Hibernate Subquery

In this section we will discuss about hibernate Subquery.

Hibernate Subquery

In this section we will discuss about hibernate Subquery.

Hibernate Subquery:

Hibernate Subqueries are surrounded by parentheses ().Hibernate supports subqueries within queries for database that support subselect.
By writing subqueries you can group, order and aggregate your resultant of query by using where clause /in clause.
Subqueries executed before the query run.
You can write subquery by using native SQL ,HQL or Criteria.

Example : In this example we are writing subquery to find out employee whose id is equal to 3 or greater than 5.

Here is main class code -

package net.roseindia.main;

import java.util.*;

import net.roseindia.table.Employee;
import net.roseindia.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class MainClass {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession(); // session is opened

String hql = "SELECT,, emp.salary, emp.dateOfJoin from Employee emp " +
"WHERE IN (SELECT FROM emp Employee WHERE OR>5) group by";
Query query = session.createQuery(hql);

List objectList = query.list();
Iterator iterator = objectList.iterator();
System.out.println("Emp Id\tEmployee Name\tSalary\tDate of Join");
while (iterator.hasNext()) {
Map map = (Map);
System.out.print("\t" + map.get("1"));
System.out.print("\t" + map.get("2"));
System.out.print("\t" + map.get("3"));

session.close(); // session is closed


Hibernate: select employee0_.emp_id as col_0_0_, as col_1_0_, employee0_.salary as col_2_0_, employee0_.date_of_join as col_3_0_ from employee employee0_ where employee0_.emp_id in (select employee0_.emp_id from employee employee0_ where employee0_.emp_id=3 or employee0_.emp_id>5) group by employee0_.emp_id
Emp Id   Employee Name    Salary      Date of Join
3        Mac              15000       2003-12-23 00:00:00.0
6        Linda            20000       2010-06-12 00:00:00.0

Download complete source code



Posted on: August 7, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Hibernate Subquery  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
August 23, 2012
Very weel

I loved your post... Tranks!