Hibernate Left Join Example | Left Join Hibernate | Hibernate Join Online Tutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show you how to work with Hibernate Left Join.
The Left Join is a keyword in SQL, which returns all data from the left-hand side table and matching records from the right-hand side table. We can see the NULL values from the right side if there is no match.
We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table’s primary key as a child table’s foreign key.
For this tutorial, I am going to take the two tables like Customer and Items; these two are having one to many relationship. That means one Customer can have multiple Items.
 Create customer and item tables with data to apply left join.
package com.otp.hibernate.pojo;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "cid")
    private int customerId;
    @Column(name = "cname", length = 15)
    private String customerName;
    @Column(name = "ccity", length = 20)
    private String customerCity;

    @OneToMany(targetEntity = Item.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "cid",referencedColumnName="cid")
    private List items;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerCity() {
        return customerCity;
    }

    public void setCustomerCity(String customerCity) {
        this.customerCity = customerCity;
    }

    public List getItems() {
        return items;
    }

    public void setItems(List items) {
        this.items = items;
    }

}

Create Item Class
package com.otp.hibernate.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="item")
public class Item {
    @Id
    @Column(name="iid")
    private int itemId;
    @Column(name="iname")
    private String itemName;
    @Column(name="price")
    private int price;

    public int getItemId() {
        return itemId;
    }

    public void setItemId(int itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}

Create Hibernate Configuration File :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.springframework.samples</groupId>
  <artifactId>Hibernate-LeftJoin-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.0.Final</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.34</version>
    </dependency>
  </dependencies>
</project>

Create Hibernate Utility Class
package com.otp.hibernate.pojo;

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

public class HibernateUtility{
    private static SessionFactory factory;

    private HibernateUtility() {
    }

    public synchronized static SessionFactory getSessionFactory() {
        if (factory == null) {
            factory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        }
        return factory;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new RuntimeException("Clone not Supported");
    }

}


Query For Hibernate Left Join on the above tables, the same will be implemented in below class as hql select query.
 select c.customerName, c.customerCity, i.itemName,i.price from Customer c left join c.items i;
Main.java
import java.util.Iterator;
import java.util.List;

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

import com.otp.hibernate.pojo.HibernateUtility;

public class Main {

    public static void main(String[] args) {
        SessionFactory factory = HibernateUtility.getSessionFactory();
        Session session = factory.openSession();
        Query qry= session.createQuery("select c.customerName, c.customerCity, i.itemName,i.price from Customer c "
                + "left join c.items i");
        List l = qry.list();
        Iterator it=l.iterator();
        while(it.hasNext())
        {
            Object rows[] = (Object[])it.next();
            System.out.println(rows[0]+ " -- " +rows[1] + "--"+rows[2]+"--"+rows[3]);
        }
        session.clear();
        session.close();
    }

}

Happy Learning 🙂


Hibernate-LeftJoin-Example

File size: 14 KB
Downloads: 1169


Hibernate One To Many Using Annotations
Basic Hibernate Example with XML Configuration
Many to One Mapping in Hibernate Example
Hibernate 4 Example with Annotations Mysql
Hibernate Table per Class strategy Annotations Example
Custom Generator Class in Hibernate
Calling Stored Procedures in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate groupby criteria HQL query Example
Hibernate Right Join Example
Thread  join Example in Java
Fork and Join in Java 7 Example
What is Hibernate
Top 10 Advantages of Hibernate
Hibernate session differences between load() and get()

Hibernate One To Many Using Annotations
Basic Hibernate Example with XML Configuration
Many to One Mapping in Hibernate Example
Hibernate 4 Example with Annotations Mysql
Hibernate Table per Class strategy Annotations Example
Custom Generator Class in Hibernate
Calling Stored Procedures in Hibernate
Hibernate Filter Example Xml Configuration
Hibernate groupby criteria HQL query Example
Hibernate Right Join Example
Thread  join Example in Java
Fork and Join in Java 7 Example
What is Hibernate
Top 10 Advantages of Hibernate
Hibernate session differences between load() and get()
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache