JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Association and Collection Mapping

Relationships

Relationship Types:-

  • Association
     --Mapping relationships between two objects

    Example

    --Account and AccountOwner
  • Collection
    --Collection of values representing individual pieces of data
         Example
  •         Map of holidays
  •         String array of months 


Relationship Dimensions
  • Relationships between entities can exist in multiple ways
    • Multiplicity
      • How many on each side of the relationship?
    • Directionality
      • From which side(s) of the relationship can you access the other?
  • A single object may have multiple relationships

Relationship Multiplicity

One-to-Many

– A singleAccount has manyTransactions
– Reverse of a many-to-one relationship

• Many-to-One
– Multiple Transactions belong to a single account
– Reverse of a one-to-many relationship

• One-to-One
– A single AccountOwner has a single HomeAddress
– A single HomeAddress has a single AccountOwner

• Many-to-Many
– Multiple Accounts have multiple AccountOwners
– Often realized through two one-to-many relationships
          • A single Account has multiple AccountOwners
          • A single AccountOwner has multiple Accounts

Relationship Directionality

Unidirectional
  –Can only traverse objects from one side of the relationship
  – Example: Account : Transaction
       • Given an Account object, can obtain related Transaction objects.
       • Given a Transaction object, cannot obtain related Account object.

Bidirectional
    – Can traverse objects from both sides of the relationship
    – Example: Account : Transaction
         • Given an Account object, can obtain related Transaction objects.
         • Given a Transaction object, can obtain related Account object.


Collections in Domain Objects

Must always use Interfaces
       – Collection, List, Map, Set, etc…
• Should be instantiated right away
       – Not delegated to Constructor, Setter


Java-to-Database Through Hibernate

Association & Collection mapping tags practically identical
• Hibernate Collection Types
             – <set>
                   • Unordered/Ordered, requiring value column
            – <map>
                  • Unordered/Ordered, requiring key and value columns
             – <list>
                 • Ordered, requiring an index column on the referenced object table
            -<array>
                 • Map to Java Type and Primitive Arrays
                 • Ordered, requiring an index column on the referenced object table



Hibernate Mapping Many-to-One

In this example you will learn how to map many-to-one relationship using Hibernate. Consider the following relationship between Employee and Address entity.


According to the relationship many students can have the same address.

To create this relationship you need to have a EMPLOYEE and ADDRESS table.

Employee .java

package mypack;

public class Employee {

  private long empid;
  private String empname;
  private Address empaddress;

  public Employee() {
  }

  public Employee(String empname, Address empaddress) {
    this.empname = empname;
    this.empaddress = empaddress;
  }

  public long getEmpid() {
    return empid;
  }

  public void setEmpid(long empid) {
    this.empid = empid;
  }

  public String getEmpname() {
    return empname;
  }

  public void setEmpname(String empname) {
    this.empname = empname;
  }

  public Address getEmpaddress() {
    return empaddress;
  }

  public void setEmpaddress(Address empaddress) {
    this.empaddress = empaddress;
  }

}

Address.java

package mypack;

public class Address implements java.io.Serializable {

  private long addressId;
  private String street;
  private String city;
  private String state;
  private String zipcode;

  public Address() {
  }

  public Address(String street, String city, String state, String zipcode) {
    this.street = street;
    this.city = city;
    this.state = state;
    this.zipcode = zipcode;
  }

  public long getAddressId() {
    return this.addressId;
  }

  public void setAddressId(long addressId) {
    this.addressId = addressId;
  }

  public String getStreet() {
    return this.street;
  }

  public void setStreet(String street) {
    this.street = street;
  }

  public String getCity() {
    return this.city;
  }

  public void setCity(String city) {
    this.city = city;
  }

  public String getState() {
    return this.state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public String getZipcode() {
    return this.zipcode;
  }

  public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
  }

}

HibernateUtil.java

package myutil;

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

public class HibernateUtil {
  private static final SessionFactory sessionFactory;
  static {
    try {
      sessionFactory = new Configuration().configure()
          .buildSessionFactory();
    catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }
}

Main.java

package mypack;

import myutil.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main {

  public static void main(String[] args) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      Address address = new Address("Babar Road""Delhi""New delhi""110005");

      Employee emp1 = new Employww("Shankar", address);
      Employee emp2 = new Employee("Javed", address);
      session.save(emp1);
      session.save(emp2);
      transaction.commit();
    catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    finally {
      session.close();
    }

  }

}
hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/
hibernate-configuration-3.0.dtd"
>
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>

    <property name="hibernate.connection.url">
jdbc:oracle:thin:
@localhost:1521:XE</property>
    <property name="hibernate.connection.username">
system</property>

    <property name="connection.password">manager</property>

    <property name="hibernate.dialect">
org.hibernate.dialect.OracleDialect</property>

    <property name="hbernate.show_sql">
rue</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping resource="Employeet.hbm.xml" />
    <mapping resource="Address.hbm.xml" />
  </session-factory>
</hibernate-configuration>

To create the EMPLOYEE and ADDRESS table you need to create the following hibernate mapping files.

Employee.hbm.xml is used to create the EMPLOYEE table.

01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="mypack.Employee" table="EMPLOYEE">
07.       
08.        <id name="empid" type="long" column="EMP_ID">
09.            <generator class="native" />
10.        </id>
11.        <property name="empname" type="string"
length=
"100" not-null="true" column="EMP_NAME" />
12.        <many-to-one name="studentAddress"
class
="mypack.Address" column="EMP_ADDRESS"
cascade="all" not-null="true" />
13.    </class>
14.</hibernate-mapping>
  • The many-to-one element is used to create the many-to-one relationship between the Employee and Address entities.
  • The cascade option is used to cascade the required operations to the associated entity
  • If the cascade option is set to all then all the operations will be cascaded. 
  • For instance when you save a Employee object, the associated Address object will also be saved automatically.

Address.hbm.xml is used to create the ADDRESS table.

01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="com.vaannila.student.Address" table="ADDRESS">
07.        <meta attribute="class-description">This class contains the student's address
08.            details.</meta>
09.        <id name="addressId" type="long" column="ADDRESS_ID">
10.            <generator class="native" />
11.        </id>
12.        <property name="street" column="ADDRESS_STREET" type="string" length="250" />
13.        <property name="city" column="ADDRESS_CITY" type="string" length="50" />
14.        <property name="state" column="ADDRESS_STATE" type="string" length="50" />
15.        <property name="zipcode" column="ADDRESS_ZIPCODE" type="string" length="10" />
16.    </class>
17.</hibernate-mapping>

Download Zip Code

OUTPUT:

On executing the Main class you will see the following output.

Student tables has two records

The Address table has one records


 

Each student record points to same address record, this illustrate the many-to-one mapping

Hibernate Mapping One-to-One

In this example you will learn how to map one-to-one relationship using Hibernate. Consider the following relationship between Employee and Address entity.


According to the relationship each student should have a unique address.

To create this relationship you need to have a EMPLOYEE and ADDRESS table.

We use the many-to-one element to create the one-to-one relationship between the Employee and Address entities. We do this my making the EMP_ADDRESS column unique in the EMPLOYEE table.



01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="mypack.Employee" table="EMPLOYEE">
07.        
08.        <id name="empid" type="long" column="EMP_ID">
09.            <generator class="native" />
10.        </id>
11.        <property name="empname" type="string"
length=
"100" not-null="true" column="EMP_NAME" />
12.        <many-to-one name="empaddress"
class
="mypack.Address" column="EMP_ADDRESS"
cascade="all" not-null="true" unique="true" />
13.    </class>
14.</hibernate-mapping>

Download Zip Code

On executing the Main class you will see the following output


Employee  tables has two records

The Address table has two records


 

Each employee  record points to a different address record, this illustrate the one-to-one mapping

Hibernate Mapping One-to-Many

In this example you will learn how to map one-to-many relationship using Hibernate. Consider the following relationship between Employee and Phone entity.

According to the relationship a employee can have any number of phone numbers.

To create this relationship you need to have a EMPLOYEE  PHONE and EMPLOYEE_PHONE table.

To create the EMPLOYEE and PHONE table you need to create the following hibernate mapping files.

Student.hbm.xml is used to create the EMPLOYEE and EMPLOYEE_PHONE table.

01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="mypack.Employee" table="EMPLOYEE">

08.        <id name="empid" type="long" column="EMP_ID">
09.            <generator class="native" />
10.        </id>
11.        <property name="empname" type="string"
 
not-null="true" length="100" column="EMP_NAME" />
12.        <set name="empphonenumbers" table="EMPLOYEE_PHONE" cascade="all">
13.            <key column="EMP_ID" />
14.            <many-to-many column="PHONE_ID" unique="true"
class="mypack.Phone" />
15.        </set>
16.    </class>
17.</hibernate-mapping>

We use many-to-many element to create the one-to-many relationship between the EMPLOYEE and Phone entities. Since a employee can have any number of phone numbers we use a collection to hold the values. In this case we use Set. Many-to-many element is usually used to create many-to-many relationship, here we place the unique constraint on the PHONE_ID column, this makes the relationship one-to-many.

Phone.hbm.xml is used to create the PHONE table.

01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="mypack.Phone" table="PHONE">
07.       
09.        <id name="phoneid" type="long" column="PHONE_ID">
10.            <generator class="native" />
11.        </id>
12.        <property name="phonetype" type="string"
 
length="10"
column="PHONE_TYPE" />
13.        <property name="phonenumber" type="string"
 
length="15" column="PHONE_NUMBER" />
14.    </class>
15.</hibernate-mapping>

Main.java

package mypack;

import java.util.HashSet;
import java.util.Set;

import myutil.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main {

  public static void main(String[] args) {
    Session session = HibernateUtil.
getSessionFactory
().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();

      Set<Phone> phoneNumbers = new HashSet<Phone>();
      phoneNumbers.add(new Phone("house""25820209"));
      phoneNumbers.add(new Phone("mobile""9810257688"));

      Employee emplyee = new Employee("Shankar", phoneNumbers);
      session.save(employee);

      transaction.commit();
    catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    finally {
      session.close();
    }

  }

}

Download Zip Code


Now create the hibernate configuration file and add all the mapping files

On executing the Main class you will see the following output.

Employee tables has one records

The Phone table has two records



EMPLOYEE_PHONE has two records to link the employee and phone record



Each employee record points to a different phone record, this illustrate the one-to-many mapping

Hibernate Mapping Many-to-Many


In this example you will learn how to map many-to-many relationship using Hibernate. Consider the following relationship between Employee  and Project entity.

According to the relationship a employee  can involved  in any number of projects and the project can have any number of employees.

To create this relationship you need to have a EMPLOYEE ,  PROJECT  and EMP_PROJECT  table. 

package mypack;

public class Project {

  private long projectid;
  private String projectname;

  public Project(String projectname) {

    this.projectname = projectname;
  }

  public long getProjectid() {
    return projectid;
  }

  public void setProjectid(long projectid) {
    this.projectid = projectid;
  }

  public String getProjectname() {
    return projectname;
  }

  public void setProjectname(String projectname) {
    this.projectname = projectname;
  }

}

To create the EMPLOYEE and PROJECT   tables you need to create the following hibernate mapping files.

Employee.hbm.xml is used to create the EMPLOYEE and EMP_PROJECT   table.


01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03."-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04."http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.    <class name="mypack.Employee" table="EMPLOYEE">
07.        
08.        <id name="empid" type="long" column="EMP_ID">
09.            <generator class="native" />
10.        </id>
11.        <property name="empname" type="string"
length="100" not-null="true" column="EMP_NAME" />
12.        <set name="projects" table="EMP_PROJECT" cascade="all">
13.            <key column="EMP_ID" />
14.            <many-to-many column="PROJECT_ID" 
class
="mypack.Project" />
15.        </set>
16.    </class>
17.</hibernate-mapping>

We use many-to-many element to create the many-to-many relationship between the Employee and Project entities. Since a employee can invloved  in any number of projects we use a collection to hold the values. In this case we use Set.

Project.hbm.xml is used to create the PROJECT table

01.<?xml version="1.0"?>
02.<!DOCTYPE hibernate-mapping PUBLIC
03.    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
04.    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
05.<hibernate-mapping>
06.<class name="mypack.Project" table="PROJECT">
07.    
10.    <id name="projectid" type="long" column="PROJECT_ID">
11.        <generator class="native"/>
12.    </id>
13.    <property name="projectname" type="string" column="PROJECT_NAME"/>  
14.</class>
15.</hibernate-mapping>


Main.java

package mypack;

import java.util.HashSet;
import java.util.Set;

import myutil.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Main {

  public static void main(String[] args) {

    Session session = HibernateUtil.getSessionFactory()
.openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();

      Set<Project> projects = new HashSet<Project>();
      projects.add(new Project("JAVA"));
      projects.add(new Project("DOT NET"));

      Employee emp1 = new Employee("Shankar", projects);
      Employee emp2 = new Employee("Javed", projects);
      session.save(emp1);
      session.save(emp2);

      transaction.commit();
    catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    finally {
      session.close();
    }

  }
}

Download Zip Code

Now create the hibernate configuration file and add all the mapping files



On executing the Main class you will see the following output.


EMPLOYEE  tables has one records

The PROJECT  table has two records



EMP_PROJECT  has two records to link the employee and project record


Exach employee has involved in the same two projects, this illustrates the many-tomany mapping.