HQL Inner join Query Hibernate

HQL Inner join Query Hibernate

Using HQL you could join two tables. Below is sample java class which shows how to join two table and get data from it.

Note: This class is extension of previous tutorial. If you are interested to see full working example with all set up please refer this tutorial Hibernate One To Many Annotation Example

package com.javahonk;

import java.util.List;

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

import com.javahonk.bean.Child;
import com.javahonk.bean.Mother;
import com.javahonk.util.HibernateUtil;

public class HQLJoin {
    
    static SessionFactory sf = HibernateUtil.getSessionFactory();

    public static void main(String[] args) {

        Session session = sf.openSession();

        System.out.println("Inner Join query example 1\n");

        Query query = session.createQuery("from Mother as m inner join m.childs "
                + "as c where m.motherId=4 and c.mother.motherId=4");
        

        List<Object[]> list = query.list();
        
        for (Object object : list) {
            Object[] li = (Object[])object;
            for(Object liItem:li){
                
             if (liItem instanceof Mother) {
                System.out.println(((Mother)liItem).getFirstName());        
             }else {
                System.out.println(((Child)liItem).getChildId());   
             }
                
            }
        }
        

        session.close();

    }
}

Output:

HQL Inner join Query Hibernate

 

For more information about HQL please read this hibernate official tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *