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



Home Answers Viewqa Hibernate Hibernate Association and join
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


narendram
Hibernate Association and join
2 Answer(s)      3 years and 8 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 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
Hibernate Inner Join
In this section, you will learn how to do Inner 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
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 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
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
Advertisements
 

 

 

DMCA.com