Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
 
Associations and Joins 
 

This section includes a brief introduction about Associations and Joins along with examples.

 

Associations and Joins

                         

This section includes a brief introduction about Associations and Joins along with examples.

Association mappings: Association mappings comes in the list of the most difficult thing to get right. This section includes the canonical cases one by one. Here we starts the section from unidirectional mappings and comes to the bi-directional cases.

We'll include the classification of associations that whether they map or not to an intervening join table and by multiplicity.

Here we are not using the Nullable foreign keys since these keys do not require good practice in traditional data modeling. Hibernate does not require the foreign keys since mappings work even if we drop the nullability constraints.

Hibernate HQL Inner Join

Hibernate's HQL language is not capable for handling the "inner join on" clauses. If our domain entity model  includes relationships defined between the related objects then the query like this 

Query query = session.createQuery("from Car car inner join Owner owner where owner.Name ='Vinod'");

will work. HQL keeps the information of joining the Car and Owner classes according to the association mapping contained in the hbm.xml file. Since the association information is defined in the mapping file so there is no need to stipulate the join in the query. In the above query "from Car car where car.Owner.Name='Vinod'" will work too. Initialization of the collections and many-to-one mapping requires the explicit joins just to avoid lazy load errors.

A unidirectional one-to-many association on a foreign key is rarely required.

<?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="net.roseindia.Dealer">
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <bag name="product" inverse="
true" 
cascade="all,delete-orphan">
        <key column="did"/>
        <one-to-many class="
net.roseindia.Product"
/>
      </bag>

   </class>
</hibernate-mapping>

A unidirectional one-to-many association on a foreign key is rarely required.

<?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="net.roseindia.Product">
      <id name="id" type="int">
         <generator class="increment"/>
      </id>

      <property name="name" type="string"/>
      <property name="did" type="int"/>
      <property name="price" type="double"/>
      <many-to-one name="dealer" class="
net.roseindia.Dealer" 
column="did" 
insert=
"false" update="false"/>

   </class>
 
</hibernate-mapping>

Here is the hibernate code:

In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.

package net.roseindia;

import java.util.Iterator;
import java.util.List;

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

public class Join {

  /**
   @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Session sess = null;
    try{
      SessionFactory fact = new 
Configuration
().configure().buildSessionFactory();
      sess = fact.openSession();
      String sql_query = "from 
Product p inner join p.dealer as d"
;
      Query query = sess.createQuery(sql_query);
      Iterator ite = query.list().iterator();
      System.out.println("Dealer 
Name\t"
+"Product Name\t"+"Price");
      while ite.hasNext() ) {
          Object[] pair = (Object[]) ite.next();
          Product pro = (Productpair[0];
          Dealer dea = (Dealerpair[1];
          System.out.print(pro.getName());
          System.out.print("\t"+dea.getName());
          System.out.print("\t\t"+pro.getPrice());
          System.out.println();
      }
      sess.close();
    }
    catch(Exception e ){
      System.out.println(e.getMessage());
    }

  }

}

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select product0_.id as id1_0_, dealer1_.id as id0_1_, product0_.name as name1_0_, product0_.did as did1_0_, product0_.price as price1_0_, dealer1_.name as name0_1_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id

Dealer Name      Product Name      Price

Computer            Agrawal               23000.0

Keyboard            Agrawal               1500.0

Computer            Agrawal                100.0

Mobile                Mohan                   15000.0

PenDrive             Mohan                   200.0

Laptop                Ritu                        200.0

HardDisk             Ritu                       2500.0

                         

» View all related tutorials
Related Tags: sql c hibernate api com class ant comparison import io property method sed const operators expression operator port criteria name

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

2 comments so far (
post your own) View All Comments Latest 10 Comments:

This is a very good head starter tutorial. In one day you can jump on to hibernate. I have a suggestion that the author should use the same database and tables through out the tutorial. In Criteria and Projection, examples are different from the insurance database

Posted by Salman on Tuesday, 12.2.08 @ 19:50pm | #82296

Can anyone help me with inner joins. I am trying to build a query similar to below

SELECT s from School s, Address a where s.id=a.id

I am trying to fetch all those records from School table which has id number equal to the one in address table. I am trying to use inner jon and i am getting errors

The query I have built is

from School s inner join Address a with s.id=a.id


Please correct me if i am wrong. I have also set the mapping params in the .hbm.xml file

Thanks

Posted by Anuradha on Thursday, 05.8.08 @ 23:26pm | #58958

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
Search Tutorials:

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.