Home Answers Viewqa Hibernate Hibernate Association and join

 
 


narendram
Hibernate Association and join
2 Answer(s)      2 years and 2 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...

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 Pages:
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
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
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
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 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
Hibernate Left Outer Join
In this section, you will learn how to do Left 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 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
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 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
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 - Hibernate
hibernate  wts the use of inverse in hibernate? can any one explain the association mapping(1-1,1-many,many-1,many-many
Hibernate Outer Join
In this section, you will learn about types of outer joins in Hibernate
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
Hibernate delete a row error - Hibernate
Hibernate delete a row error  Hello, I been try with the hibernate delete example (http://www.roseindia.net/hibernate/hibernate-delete.shtml... - Hibernate 3.0rc1 10:46:41,397 INFO Environment:469 - hibernate.properties
Complete Hibernate 4.0 Tutorial
Hibernate Self Join Mapping Hibernate One to Many Self Join using Annotations Hibernate Many to Many Self Join using... Joins in Hibernate Hibernate Inner Join
Hibernate code problem - Hibernate
Hibernate code problem  how to write hibernate Left outer join program
Hibernate - Hibernate
Hibernate   Dear sir Thanks for your previous answers its really... ,hibernate, jboss, oracle) one is 1) Express and 2) MDM(All master data... 192.168.1.2 using hibernate(Schema name Express) In MDM i am connecting
Join Point
Join Point  What is a join point in Spring
hibernate - Hibernate
Hibernate; import org.hibernate.Session; import org.hibernate.*; import...|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined...   Hi Radhika, i think, you hibernate configuration
Hibernate 3.1.3 Released
Hibernate 3.1.3 Released Back to Hibernate Tutorials Page Hibernate... service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition
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 training
About Hibernate - Hibernate
About Hibernate  What is Hibernate? How can i learn it fast.  ... object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association
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
Polymorphism in Hibenate - Hibernate
Polymorphism in Hibenate  Hi, How polymorphism inheritance and association achieved in hibernate. Thank u in advance
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 Criteria Query
to the result set is added. createAlias () Join an association, assigning...Hibernate Criteria Query In this tutorial you will learn about the Hibernate Criteria Query. Hibernate provides an API for writing the dynamic query
Need for hibernate - Hibernate
Need for hibernate  Can anyone say why should we go for hibernate?   Hi friend, Advantages of hibernate : It is based on object... solution. In Jdbc we use .properties file and in hibernate we use .xml file
Hibernate 3.1.1 Released
Hibernate 3.1.1 Released Back to Hibernate Tutorials Page Hibernate.... Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections
Reagrsding Hibernate joins - Hibernate
Reagrsding Hibernate joins  Hi, I am trying to make join in Hibernate...{ // This step will read hibernate.cfg.xml and prepare hibernate for use..."?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
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
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
Java - Hibernate Interview Questions
Java  how to write a sql join in hibernate query language?  Hi Friend, Please visit the following link for more help on the HQL join and many more examples: http://www.roseindia.net/hibernate http
JAVA - Hibernate
JAVA  hello friends please answer me. 1. what is hibernate...? 2. why hibernate..? 3. Hibernate Vs JDBC...? plz plz plz answer me, i have seminar in that topic..  Hi friend, Hibernate It is a free, open
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 @ManyToOne persisting problem - Hibernate
Hibernate @ManyToOne persisting problem  hello, In my apllication... is using a join table. I followed examples I found on internet and at books. So I..., including join table, are created. When I push save button, the student and the class
Hibernate Aggregate Functions(Associations and Joins)
Hibernate Aggregate Functions(Associations and Joins... understand about the aggregate function of Hibernate with the help of example.  In Hibernate HQL queries are capable of returning the results of the aggregate
Detachedcriteria in hibernate
in hibernate for given Query?   Detached Criteria query is a facility provide by Hibernate to write criteria queries in ?detached mode?, where hibernate...()); System.out.println("Date of Join : " + employee.getDateOfJoin
Hibernate Query Language
Hibernate Query Language   Explain Hibernate Query Language(HQL) of Hibernate?   Hi Samar, Hibernate Query Language is a library... like inheritance, polymorphism and association. Thanks
Hibernate joining multiple tables
Hibernate joining multiple tables  In join sample program, what do we mean by the line? String sql_query = "from Product p inner join p.dealer as d"; what does it mean? Product p inner join p.dealer as d   Hello
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 How To
Hibernate How To Adding the ordering ability in your Hibernate... to add ordering ability to in Hibernate Application when using... to serach the result using Hibernate Criteria Finding Unique ResultIn
Please convert this SQL query to hibernate - Hibernate
select a.msisdn,sum(b.amount) 'amount' from account a inner join...://www.roseindia.net/hibernate/hibernate-aggregate-functions.shtml http://www.roseindia.net/hibernate/index.shtml Hope that it will be helpful for you. Thanks
What is outer join?Explain with examples.
What is outer join?Explain with examples.  What is outer join?Explain with examples
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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.