Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Hibernate Hibernate Association and join

Have Programming Question? Ask it here!
 
 
 


narendram
Hibernate Association and join
2 Answer(s)      3 years and 5 months ago
Posted in : Hibernate


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...


Advertisement
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... Association The Hibernate ORM supports the association relationships... of Hibernate Association mappings Hibernate framework supports following types
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 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 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 Join
query, one of them is Hibernate Criteria Join which performs join operation... and returns the value. Example of Hibernate Criteria join: SelectCriteria.java... Criteria Join Hibernate Criteria Examples
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
Hibernate Outer Join
In this section, you will learn about types of outer joins in Hibernate
Join Point
Join Point  What is a join point in Spring
Outer join
Outer join  hii, What is outer join? Types of outer join??   hello, There are two type of outer join:- A. Left Outer Join B. Right Outer Join The Left Outer Join returns all the rows from the Left Table
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 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
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
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
Hibernate Training
Hibernate Training     Hibernate Training Get trained in Hibernate 3 with experts. Hibernate.... Hibernate training gives you skills need to use Hibernate to develop enterprise
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
upgrading sql query join
upgrading sql query join  upgrading sql query join
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
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
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
Hibernate Tutorial Roseindia
language. Roseindia Hibernate tutorials includes all the aspects of hibernate with latest updates including hibernate configuration , association relationship...Roseindia.net provides you the best Hibernate tutorials with full examples
hibernate - Hibernate
hibernate  how to write join quaries using hql  Hi satish...: http://www.roseindia.net/hibernate/hibernate-aggregate-functions.shtml http://www.roseindia.net/hibernate/associations-and-joins.shtml Thanks
What is outer join?Explain with examples.
What is outer join?Explain with examples.  What is outer join?Explain with examples
SQL Right JOIN
SQL Right JOIN       The RIGHT JOIN keyword returns you  all rows from... JOIN. Understand with Example The Tutorial illustrate an example from
MySQL LEFT OUTER JOIN
MySQL LEFT OUTER JOIN  Hi There, I need to perform LEFT OUTER JOIN... OUTER JOIN trans t ON tt.transtypeid = t.transtypeid WHERE YEAR(t.transcrtndt... The above link will provide you a good example of Left outer join
ejb3.0 join queries - EJB
ejb3.0 join queries   Hi Guys, I am new to ejb3.0 . As i am new to ejb3.0 i am unable to write join quries.i am having 3 tables...; SELECT STRAIGHT_JOIN ArticleTitle, Copyright, CONCAT_WS(' ', AuthorFirstName
Mysql 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 table on the basis
SQL LEFT JOIN
SQL LEFT JOIN       The LEFT JOIN keyword retrieve all rows from the left table (table_name1... with Example The Tutorial illustrate an example from SQL LEFT JOIN
Sql Join Query
Sql Join Query  aTable Name : TblState Stid StateName CountryId --------------------------------------------- 01 TN 01 02 KR 01 03 KL 01 04 WB 01 05 New
Help with SELECT/JOIN statement
Help with SELECT/JOIN statement  I have two tables (t1 and t2) that each have the same columns. t1 has data and t2 has changes to the data. I want a select statement that will return me all rows of t1 but, when t1.id = t2.id, I
Complete Hibernate 4.0 Tutorial
Hibernate Self Join Mapping Hibernate One to Many Self Join using Annotations Hibernate Many to Many Self Join using... Inner Join Hibernate Left Outer Join
Polymorphism in Hibenate - Hibernate
Polymorphism in Hibenate  Hi, How polymorphism inheritance and association achieved in hibernate. Thank u in advance
Java Cross Join MySQL
Java Cross Join MySQL In this section we will read about how the two tables can be joined using cross join in MySQL. Here we will see cross joining using a simple example. Cross Join in SQL joins two tables. These two tables are joined
Natural Right Join
Natural Right Join       In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join
Natural Left Join
Natural Left Join       In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join
Java Thread Join
Java Join method join the next thread at the end of the current thread After current thread stops execution then next thread executes. Java Join Thread Example public class join implements Runnable { @Override public
PHP array join
Join function add all the elements of the given array into a single string... function. PHP Array Join() Example <?php $myarray=array("c"=>...($myarray); $array1=join($myarray); echo "<br>"; print_r($array1
HIBERNATE
HIBERNATE   What is difference between Jdbc and Hibernate
hibernate
hibernate  what is hibernate flow
hibernate
hibernate  what is hibernate listeners
Advertisements
 

 

 

DMCA.com