VisualBuilder
  Home > Java > Tutorials > Managing Associations - Hibernate Tutorial
Tell a friend
Link to us
Total Members
      Members: 84661
     
Sitemap Forum Chat
Home
Hibernate Tutorial Home
1 . Introduction to Java Hibernate
2 . Introduction to Hibernate
3 . The Object/Relational Mapping Problem
4 . JDBC
5 . The Hibernate Alternative
6 . Hibernate Architecture and API
7 . Setting Up Hibernate
8 . Setting up Hibernate - Add the Hibernate libraries
9 . Registration Case Study
10 . Creating the Hibernate Configuration
11 . Writing the first Java File
12 . Writing the mapping file
13 . Writing the Business Component
14 . Writing the Test Client
15 . Managing Associations
16 . Finding by primary key
17 . Hibernate Query Language (HQL)
18 . Using native SQL
19 . Using Criteria Queries
20 . Using Ant to run the project
21 . Using Middlegen to generate source
22 . Review and the next steps
 
 
Java Home
Java Members (27610)
Java Member Articles ( 40 )
Java Discussion (273)
Java Q & A ( 153 )
- Java Ask Question
- Java Questions
- Java Unanswered Questions
Java Resources
Java Source Code (1095)
Java Articles (550)
Java Blogs (118)
Java Jobs (797)
Java Components (84)
Java Books (169)
Java Websites (126)
Java News (103)
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.Net Security,Internationalisation And Deployment
ASP.NET Tutorial
C# Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (451 )
Source Code (3275 )
Articles (359 )
Books (372 )
Components (1596 )
News (892 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise

Java hibernate Tutorial
 Managing Associations
  << Prev: Writing the Test Client Next: Finding by primary key >>

Association is a relationship of one class to another class known as 'relationships' in database terminology. Usually the database design involves the master detail tables to represent the relationship of one entity to another. Struts provides a mechanism to manage one-to-many and many-to-many relationships. Before moving forward,let's create the necessary database tables to show associations.


Let's create a table phone_numbers to represent phone numbers of a user. Following script can be used to create the table in Oracle.


CREATE TABLE PHONE_NUMBERS
(
    USER_ID NUMBER REFERENCES USERS(USER_ID),
    NUMBER_TYPE VARCHAR(50),
    PHONE NUMBER,
    PRIMARY KEY(USER_ID,NUMBER_TYPE)
);


The same table can be created in MySQL using the script given below.


CREATE TABLE PHONE_NUMBERS
(
    USER_ID NUMERIC NOT NULL REFERENCES USERS(USER_ID),
    NUMBER_TYPE CHAR(50) NOT NULL,
    PHONE NUMERIC,
    PRIMARY KEY(USER_ID,NUMBER_TYPE)
);


We have two tables in the database: USERS and the PHONE_NUMBERS with one to many relationship such that one User many contain 0 or more phone numbers. Create a class PhoneNumber and create its mapping file following the steps to create User class. The code for the PhoneNumber class is shown below.


package com.visualbuilder.hibernate;
import java.io.Serializable;
/**
* PhoneNumber
* @author VisualBuilder
*/
public class PhoneNumber implements Serializable
{
private long userId = 0;
private String numberType = "home";
private long phone = 0;
public String getNumberType() {
return numberType;
}
public void setNumberType(String numberType) {
this.numberType = numberType;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}

Note that we have made the PhoneNumber class Serializeable. This is because we need a composite key in this class,and Hibernate requires tat the class that represents the composite key must be Serializeable. The mapping file 'PhoneNumber.hbm.xml' contains following text.


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 
<hibernate-mapping>

  <class name="com.visualbuilder.hibernate.PhoneNumber" table="PHONE_NUMBERS"
>
     
<composite-id>
            <key-property column="USER_ID"  name="userId" type="java.lang.Long"
/>
            <key-property column="NUMBER_TYPE"  name="numberType" type="java.lang.String"
/>
       
</composite-id>
 
        <property name="phone" type="java.lang.Long"
>
            <column name="PHONE" precision="22" scale="0"
/>
       
</property>
 
 
</class>
</hibernate-mapping>
 


Add the mapping resource for PhoneNumber in hibernate.cfg.xml file. To do this,locate the line <mapping resource="com/visualbuilder/hibernate/User.hbm.xml" /> in the hibernate.cfg.xml file and add the following line just after this line.


<mapping resource="com/visualbuilder/hibernate/PhoneNumber.hbm.xml" />

We want to write few lines of code so that when we select a user,we automatically get all the phone numbers associated with this user. To do this,add a method 'getPhoneNumbers' that returns a list of users in class User and 'setPhoneNumbers' that takes a List as argument. The complete listing of class User after adding these two methods is shown below.


package com.visualbuilder.hibernate;
/**
* @author VisualBuilder
*
*/
public class User {
private long userId = 0;
private String firstName = "";
private String lastName = "";
private int age = 0;
private String email = "";
private java.util.Set phoneNumbers = new java.util.HashSet();
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public java.util.Set getPhoneNumbers() {

return phoneNumbers;
}
public void setPhoneNumbers(java.util.Set phoneNumbers) {
if(phoneNumbers != null)
this.phoneNumbers = phoneNumbers;
}
}

The phoneNumbers HashTable will be used to store all phone numbers associated with this User. The new changes are highlighted in gray. We have added the methods for getting and setting the phone umbers,we need to add the mapping for the phone numbers now. Add the following block in User.hbm.xml before the </class> tag.


<set name="phoneNumbers" cascade="all">
<key column="USER_ID"/>
<one-to-many class="com.visualbuilder.hibernate.PhoneNumber" />
</set>

As you can see,the tags are very simple. The cascade attribute of set tells the Hibernate how to deal with the child records when a parent is deleted  or a child is added.


Now it is the time to test our functionality. Remember the TestClient class where we had few blocks of code explaining the save,update and delete functionality. For the time being,comment the call to testDeleteUser and replace the contents of method testUpdateUser with the following code.


  PhoneNumber ph = new PhoneNumber();
  ph.setUserId(user.getUserId());
  ph.setNumberType("Office");
  ph.setPhone(934757);
  user.getPhoneNumbers().add(ph);
 
  ph = new PhoneNumber();
  ph.setUserId(user.getUserId());
  ph.setNumberType("Home");
  ph.setPhone(934757);
  user.getPhoneNumbers().add(ph);

  manager.saveUser(user);
  System.out.println("User updated with ID = " user.getUserId());
 


We are adding two phone numbers to the recently saved user objects. Note that we even don't need to save the PhoneNumber. These are automatically saved as we add them to the User. Query the database and see how these instances are persisted. Once you see the values in the database,re-enable the code to delete the User object and see what happens with the child PhoneNumber objects.


So far,we have dealt with one to many association,we can configure the Hibernate for one to one and many to many associations. For more details on how to make Hibernate configuration for other kind of associations,see http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#tutorial-associations


  << Prev: Writing the Test Client Next: Finding by primary key >>
Java Hibernate Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
 
ADVERTISEMENT
Partner List
Code Project
ASP Alliance
More
 
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising