Hibernate Association and join

Hibernate Association and join

hi, can u please tell me SQL DDL queries to create Product and Dealer table... and also tell me java code for Product and Dealer bean...

View Answers

March 17, 2011 at 3:17 PM

Exmple of Hibernate Associations and Joins using Javadb / derby database

HibernateUtil.java file

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

public class HibernateUtil {

    public static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            // Store it in the ThreadLocal variable
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

Main.java File

import java.util.*;


import org.hibernate.*;


public class Main {

    public static void main(String[] args) {
        Session session = HibernateUtil.currentSession();

            String hql = "from Product p inner join p.supplier as s";
            Query query = session.createQuery(hql);
            List results = query.list();
        displayObjectsList(results);



    }
    static public void displayObjectsList(List list)
    {
        Iterator iter = list.iterator();
        if (!iter.hasNext())
        {
            System.out.println("No objects to display.");
            return;
        }
        while (iter.hasNext())
        {
            System.out.println("---------New object-------------");
            Object[] obj = (Object[]) iter.next();

                Product p = (Product)obj[0];
                Supplier s = (Supplier)obj[1];

                System.out.println("Product ID :"+p.getId());
                System.out.println("Product Name :"+p.getName());
                System.out.println("Product Price :"+p.getPrice());
                System.out.println("Supplier ID:"+s.getId());
                System.out.println("Supplier Name :"+s.getName());
        }
    }       
}

Product.java

public class Product
{
    private int id;
    private Supplier supplier;

    private String name;

    private double price;

    public Product()
    {
        super();
    }

    public Product(String name, double price)
    {
        super();
        this.name = name;

        this.price = price;
    }


    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

    public Supplier getSupplier()
    {
        return supplier;
    }
    public void setSupplier(Supplier supplier)
    {
        this.supplier = supplier;
    }

    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
}

Supplier.java

import java.util.ArrayList;
import java.util.List;

public class Supplier
{
    private int id;
    private String name;
    private List products = new ArrayList();

    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public List getProducts()
    {
        return products;
    }
    public void setProducts(List products)
    {
        this.products = products;
    }
}

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
         <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
      <property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample;create=true;autocommit=true</property>
      <property name="hibernate.connection.username">NarendraMah</property>
      <property name="hibernate.connection.schema">APP</property>
      <property name="hibernate.connection.password">NarendraMah</property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="hibernate.connection.autommit">true</property>
      <property name="show_sql">true</property>

      <property name="dialect">org.hibernate.dialect.DerbyDialect</property>
      <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Mapping files -->
        <mapping resource="Product.hbm.xml"/>
        <mapping resource="Supplier.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Product.xml

<?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="Product" table="APP.PRODUCT">
      <id name="id" type="int" column="ID">
         <generator class="increment"/>
      </id>

      <property name="name" type="string" column="NAME"/>

      <property name="price" type="double" column="PRICE"/>
      <many-to-one name="supplier" class="Supplier" column="SUPPLIERID"/>

   </class>

   <query name="HQLpricing"><![CDATA[
       select product.price from Product product where product.price > 25.0]]>
    </query>   
   <sql-query name="SQLpricing">
      <return-scalar column="price" type="double"/>
      <![CDATA[
       select product.price from Product as product where product.price > 25.0]]>
   </sql-query>     
</hibernate-mapping>

Supplier.hbm.xml

<?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="Supplier" table="APP.SUPPLIER">
      <id name="id" type="int" column="ID">
         <generator class="increment"/>
      </id>

      <property name="name" type="string" column="NAME"/>
      <bag name="products" inverse="true" cascade="all,delete-orphan">
        <key column="supplierId"/>
        <one-to-many class="Product"/>
      </bag>


   </class>
</hibernate-mapping>

SQL Queries

create table APP.SUPPLIER
(
    ID  INTEGER NOT NULL 
        PRIMARY KEY,
    NAME  VARCHAR(20) NOT NULL  

 ); 
 create table APP.PRODUCT
(
    ID  INTEGER NOT NULL 
        PRIMARY KEY,
    NAME  VARCHAR(20) NOT NULL , 
    PRICE DOUBLE NOT NULL,
    SUPPLIERID integer not null
 );
  insert into APP.SUPPLIER values(1,'One Services');
 insert into APP.SUPPLIER values(2,'XLS Services');
 insert into APP.SUPPLIER values(3,'Infocom Services');

 insert into APP.PRODUCT values(1,'Hard Disk',2000.00,1);
 insert into APP.PRODUCT values(2,'CD',100.00,2);
 insert into APP.PRODUCT values(3,'Processor',10000.00,3);
 insert into APP.PRODUCT values(4,'Cable',150.00,1);
 insert into APP.PRODUCT values(5,'USB Drive',800.00,2);
 insert into APP.PRODUCT values(6,'Mouse',200.00,3);

March 17, 2011 at 3:18 PM

Exmple of Associations and Joins using Javadb / derby database

HibernateUtil.java file

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

public class HibernateUtil {

    public static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            // Store it in the ThreadLocal variable
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

Main.java File

import java.util.*;


import org.hibernate.*;


public class Main {

    public static void main(String[] args) {
        Session session = HibernateUtil.currentSession();

            String hql = "from Product p inner join p.supplier as s";
            Query query = session.createQuery(hql);
            List results = query.list();
        displayObjectsList(results);



    }
    static public void displayObjectsList(List list)
    {
        Iterator iter = list.iterator();
        if (!iter.hasNext())
        {
            System.out.println("No objects to display.");
            return;
        }
        while (iter.hasNext())
        {
            System.out.println("---------New object-------------");
            Object[] obj = (Object[]) iter.next();

                Product p = (Product)obj[0];
                Supplier s = (Supplier)obj[1];

                System.out.println("Product ID :"+p.getId());
                System.out.println("Product Name :"+p.getName());
                System.out.println("Product Price :"+p.getPrice());
                System.out.println("Supplier ID:"+s.getId());
                System.out.println("Supplier Name :"+s.getName());
        }
    }       
}

Product.java

public class Product
{
    private int id;
    private Supplier supplier;

    private String name;

    private double price;

    public Product()
    {
        super();
    }

    public Product(String name, double price)
    {
        super();
        this.name = name;

        this.price = price;
    }


    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

    public Supplier getSupplier()
    {
        return supplier;
    }
    public void setSupplier(Supplier supplier)
    {
        this.supplier = supplier;
    }

    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
}

Supplier.java

import java.util.ArrayList;
import java.util.List;

public class Supplier
{
    private int id;
    private String name;
    private List products = new ArrayList();

    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public List getProducts()
    {
        return products;
    }
    public void setProducts(List products)
    {
        this.products = products;
    }
}

Product.xml

<?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="Product" table="APP.PRODUCT">
      <id name="id" type="int" column="ID">
         <generator class="increment"/>
      </id>

      <property name="name" type="string" column="NAME"/>

      <property name="price" type="double" column="PRICE"/>
      <many-to-one name="supplier" class="Supplier" column="SUPPLIERID"/>

   </class>

   <query name="HQLpricing"><![CDATA[
       select product.price from Product product where product.price > 25.0]]>
    </query>   
   <sql-query name="SQLpricing">
      <return-scalar column="price" type="double"/>
      <![CDATA[
       select product.price from Product as product where product.price > 25.0]]>
   </sql-query>     
</hibernate-mapping>

Supplier.hbm.xml

<?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="Supplier" table="APP.SUPPLIER">
      <id name="id" type="int" column="ID">
         <generator class="increment"/>
      </id>

      <property name="name" type="string" column="NAME"/>
      <bag name="products" inverse="true" cascade="all,delete-orphan">
        <key column="supplierId"/>
        <one-to-many class="Product"/>
      </bag>


   </class>
</hibernate-mapping>

SQL Queries

create table APP.SUPPLIER
(
    ID  INTEGER NOT NULL 
        PRIMARY KEY,
    NAME  VARCHAR(20) NOT NULL  

 ); 
 create table APP.PRODUCT
(
    ID  INTEGER NOT NULL 
        PRIMARY KEY,
    NAME  VARCHAR(20) NOT NULL , 
    PRICE DOUBLE NOT NULL,
    SUPPLIERID integer not null
 );
  insert into APP.SUPPLIER values(1,'One Services');
 insert into APP.SUPPLIER values(2,'XLS Services');
 insert into APP.SUPPLIER values(3,'Infocom Services');

 insert into APP.PRODUCT values(1,'Hard Disk',2000.00,1);
 insert into APP.PRODUCT values(2,'CD',100.00,2);
 insert into APP.PRODUCT values(3,'Processor',10000.00,3);
 insert into APP.PRODUCT values(4,'Cable',150.00,1);
 insert into APP.PRODUCT values(5,'USB Drive',800.00,2);
 insert into APP.PRODUCT values(6,'Mouse',200.00,3);









Related Tutorials/Questions & Answers:
Hibernate Association and join
Hibernate Association and join  hi, can u please tell me SQL DDL queries to create Product and Dealer table... and also tell me java code for Product and Dealer bean
Association and join
Association and join  hi can u please add code for Product and Dealer bean
Advertisements
Hibernate association and join example
is very important concept of Hibernate framework. Hibernate association allows... data. Hibernate Association The Hibernate ORM supports the association... @ManyToMany Types of Hibernate Association mappings Hibernate
Hibernate Association
Hibernate Association  1) <bag name="product" inverse="true" cascade="all,delete-orphan"> <key column="did"/> <one-to-many class="net.roseindia.Product"/> </bag> 2) <many-to-one
Left Outer Join in Hibernate createQuery() - Hibernate
Left Outer Join in Hibernate createQuery  What is Left Outer Join in Hibernate createQuery? i'm using createQuery("select...") for my project, i have a situation using left Outer join... this createQuery(" from A left outer join
Hibernate Inner Join
In this section, you will learn how to do Inner Join in Hibernate
Hibernate Left Outer Join
In this section, you will learn how to do Left Outer Join in Hibernate
Hibernate Right Outer Join
In this section, you will learn how to do Right Outer Join in Hibernate
join multiple tables via hibernate criteria - Hibernate
join multiple tables via hibernate criteria  Dear all, i have a problem working with hibernate. i wanna join multiple tables via hibernate criteria. How can i do this operation? Thanks in advance regards Rosa
Hibernate One to Many Self Join using Annotations
In this section, you will learn one to many self join using Annotations in Hibernate
Hibernate Criteria Join
Hibernate Criteria Join API Hibernate Criteria JOIN API allows users to perform join operation. Suppose you have to perform a operation like SELECT S.*, C... on the class. Suppose you have to apply restriction on join operation
Getting exception in Assocation & Join. - Hibernate
Getting exception in Assocation & Join.  select product0_.id as id0_, dealer1_.id as id1_, product0_.name as name2_0_, product0_.did as did2_0... join Dealer dealer1_ on product0_.did=dealer1_.id where (dealer1_.id=1
Hibernate Criteria Dynamic Association Fetching
Hibernate Criteria Dynamic Association Fetching In this tutorial you will learn about the dynamic association fetching in Criteria Query. In a Criteria Query a dynamic fetching operation can be done using the fields, JOIN, SELECT
Hibernate Criteria Join
query, one of them is Hibernate Criteria Join which performs join operation... of Hibernate Criteria join: SelectCriteria.java package net.roseindia.main... Resources:ADS_TO_REPLACE_4 Hibernate Criteria Join
Hibernate Many to Many Self Join using Annotations
In this section, you will learn how to do many to many self join using Annotations in Hibernate
Hibernate Criteria Associations
Hibernate Criteria Associations In this section you will learn about Criteria Query Association in Hibernate. Association in Criteria Query may be done... with the reference of specified collection. On the other way an association can also
Join Point
Join Point  What is a join point in Spring
Hibernate Outer Join
In this section, you will learn about types of outer joins in Hibernate
ModuleNotFoundError: No module named 'association-measures'
ModuleNotFoundError: No module named 'association-measures'  Hi...: No module named 'association-measures' How to remove the ModuleNotFoundError: No module named 'association-measures' error? Thanks   Hi
ModuleNotFoundError: No module named 'openerp-association'
ModuleNotFoundError: No module named 'openerp-association'  Hi, My... named 'openerp-association' How to remove the ModuleNotFoundError: No module named 'openerp-association' error? Thanks   Hi
ModuleNotFoundError: No module named 'association-engine'
ModuleNotFoundError: No module named 'association-engine'  Hi, My... named 'association-engine' How to remove the ModuleNotFoundError: No module named 'association-engine' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'openerp-association'
ModuleNotFoundError: No module named 'openerp-association'  Hi, My... named 'openerp-association' How to remove the ModuleNotFoundError: No module named 'openerp-association' error? Thanks   Hi
ModuleNotFoundError: No module named 'association-engine'
ModuleNotFoundError: No module named 'association-engine'  Hi, My... named 'association-engine' How to remove the ModuleNotFoundError: No module named 'association-engine' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'association-measures'
ModuleNotFoundError: No module named 'association-measures'  Hi...: No module named 'association-measures' How to remove the ModuleNotFoundError: No module named 'association-measures' error? Thanks   Hi
Outer join
Outer join  hii, What is outer join? Types of outer join??ADS_TO_REPLACE_1   hello, There are two type of outer join:- A. Left Outer JoinADS_TO_REPLACE_2 B. Right Outer Join The Left Outer Join returns all
What is a "join"?
What is a "join"?  What is a "join"?   Hi, Here is the answer, The JOIN keyword is used in an SQL statement to query data from two.... Tables in a database are often related to each other with keys.A join is used
hibernate - Hibernate
hibernate  wts the use of inverse in hibernate? can any one explain the association mapping(1-1,1-many,many-1,many-many
ModuleNotFoundError: No module named 'odoo10-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo10-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo10-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo11-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'odoo12-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo12-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo12-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo8-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'odoo9-addons-oca-vertical-association'
ModuleNotFoundError: No module named 'odoo9-addons-oca-vertical-association...: ModuleNotFoundError: No module named 'odoo9-addons-oca-vertical-association' How...-association' error? Thanks   Hi, In your python environment you
Version of com.m3>openid4java-memcached-association-store dependency
List of Version of com.m3>openid4java-memcached-association-store dependency
SQL Join
SQL Join       Mysql Join Mysql Join is used to join the records from two table using join clause. The Join Clause return you the set of records from both
Hibernate Tutorials
Hibernate Tutorials Hibernate is popular open source object relational mapping... to providing mapping of Java classes to database tables, Hibernate also provides data query and retrieval facilities. In this hibernate tutorial, you
ModuleNotFoundError: No module named 'join'
ModuleNotFoundError: No module named 'join'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'join' How to remove the ModuleNotFoundError: No module named 'join' error
upgrading sql query join
upgrading sql query join  upgrading sql query join
PHP Join Tables
PHP Join Tables  i wanted to show the information from two or more table in PHP. How can i do it with the PHP Join Tables
Join the two tables in sql
Join the two tables in sql  How to join the two tables in SQL ..and return the value from common column in SQL Database
What is Self Join?
What is Self Join?  What is Self Join?   Hi, A Self Join is a type of sql join which is used to join a table to itself, particularly when... to ensure that the join statement defines an alias for both copies of the table
Hibernate code problem - Hibernate
Hibernate code problem  how to write hibernate Left outer join program
Maven Dependency openid4java-memcached-association-store >> 1.0.0
You should include the dependency code given in this page to add Maven Dependency of com.m3 >> openid4java-memcached-association-store version1.0.0 in your project
Maven Dependency openid4java-memcached-association-store >> 1.0.1
You should include the dependency code given in this page to add Maven Dependency of com.m3 >> openid4java-memcached-association-store version1.0.1 in your project
Maven Dependency openid4java-memcached-association-store >> 1.0.2
You should include the dependency code given in this page to add Maven Dependency of com.m3 >> openid4java-memcached-association-store version1.0.2 in your project
Hibernate Training
Hibernate Training     Hibernate Training Get trained in Hibernate 3 with experts. Hibernate ORM framework is very popular and widely used in the Java community. Hibernate
What is outer join?Explain with examples.
What is outer join?Explain with examples.  What is outer join?Explain with examples
Maven Repository/Dependency: com.m3 | openid4java-memcached-association-store
Maven Repository/Dependency of Group ID com.m3 and Artifact ID openid4java-memcached-association-store. Latest version of com.m3:openid4java-memcached-association-store dependencies. # Version Release Date
one-to-one bidirectional association between an abstract class and a persistent class
one-to-one bidirectional association between an abstract class and a persistent class  How do I define a bidirectional one to one association between an abstract class and a persistent class? Please help

Ads