Advertisement
Home > Hibernate Tutorial > Hibernate Mapping Bag > Hibernate Mapping ExamplePlease log in to add or reply to any matter<- requires login or
RMI Example

Home > Hibernate Tutorial > Hibernate Mapping Bag > Hibernate Mapping Example
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : admin
Title :
SessionFactory
Description : Question on Session Factory Creation
More...


Written By : Amit
Title :
Interview Questions
Description : On Hibernate
More...


Written By : Amit
Title :
mapping class hierarchy table per subclass
Description : Example
More...


Written By : Amit
Title :
ways create Hibernate SessionFactory
Description : Example
More...


Written By : Amit
Title :
Spring Hibernate Integration example
Description : Example
More...

Hibernate Mapping, Hibernate, Mapping, Bag,element , Code, Tutorial, Article
Author : guddu
Date (Year/Month/Date): 2009-12-06 Hibernate-Mapping-Bag Element example
Setting up of Environment for Examples we shall be exploring
in following articles/writings of using Hibernate related mapping
of POJO/domain objects with database tables/views

I have used following Software Environment for compilation and 
running these examples, as follows:

  • IDE (Integrated Development Environment)- Eclipse version 3.2 -
  • Java Platform version "1.6.0_17" -
  • Hibernate version 3.2 -
  • HSQLDB version 1.8.0 -
  • Advertisement
    Once all these software environment is set in the Development Environment. Now Time is to create the Eclipse example workspace and creating all the folder structures and files, including Java , XML mapping and Database objects SQL file.
  • Create a Eclipse workspace at Eclipse startup time dialog box or by navigating to "File->Switch Workspace" menu item.
  • Create a Java Project by navigating to the "File->New->Project" menu item
  • Choose "Java->Java Project" dialogbox dropdown selection
  • Fill in relevant details including the name of the Java Project at your convenience and as per your local development Java Environment
  • After creating of the Java Project, create src (as source folder) and lib (for JAR files) folders.
  • Right click the project and go to Project Properties and a dialog box appears.
  • Navigate to "Java Build Path" in the left section. And select Source tab in the right section.
  • Just make sure your source src folder is shown in the "source folders on build path" and bin as default output folder (below default output folder)
  • Following set of JAR files I have used locally in my Local Dev environment to make these example run smoothly without any design/compile time or runtime exceptions.
  •       antlr-2.7.6.jar
          asm.jar
          asm-attrs.jar
          cglib-2.1.3.jar
          commons-collections-2.1.1.jar
          commons-logging-1.0.4.jar
          dom4j-1.6.1.jar
          hibernate3.jar
          hsqldb.jar
          jta.jar
          log4j-1.2.11.jar
    
  • Right click the project and navigate to project properties.
  • Go to Java Build Path section in left, and then select Libraries Tab
  • Click Add Jars and select all the JAR files shown under Project_Name/lib folder.
  • Apply/OK these changes to the Java Project.
  • I think, above steps are essential steps to setup workspace for further development proceedings as per Hibernate examples to follow: Example case study: In an amusement park is having many rides, and each ride has certain capacity, and price associated with it. All visitors are supposed to fill-in self details such as name, age (why age! because certain rides are not meant for children below 18 years of age). Design (Class Relationship Collaboration): Major components are AmusementPark - many rides Ride - capacity Visitor - Name, age Capacity - number of seats One Visitor can choose to go for/enjoy many Rides. So we can have domain POJOs are:
    
    AmusementPark
     name of type String
     rides of type Collection of Ride
    
    Ride
     name of type String
     capacity of type Capacity
     visitors of type Collection of visitor
    
    Capacity
     size  of type int
    
    Visitor
     name of type String
     age of type int.
    
    Hibernate mappings :
    1. AmusementPark and Ride share one to many mapping 
    2. Ride and Capacity share one to one mapping
    3. Ride and AmusementPark share many to one mapping
    4. Ride and Visitor share one to many mapping.
    
    Hibernate mapping files as follows: AmusementPark-Ride.xml
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <!--
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.interview-questions-tips-forum.net
    */
    -->
    
    
    <hibernate-mapping package="com.example">
      <class name="Amusement" table="Amusement_Park">
          <id name="name" access="property" column="ap_name"/>
          <bag name="rides" cascade="persist">
            <key column="rides"/>
            <one-to-many class="Ride"/>
          </bag>
      </class>
      <class name="Ride" table="Ride_Info">
        <id name="name" access="property" column="ride_name"/>
      </class>
    </hibernate-mapping>
    
    This is the very simplest form of mapping between Amusement and Ride domain classes: Amusement.java
    
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.interview-questions-tips-forum.net
    */
    
    package com.example;
    
    import java.util.Collection;
    
    public class Amusement {
      private String name;
      private Collection rides;
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public Collection getRides() {
        return rides;
      }
      public void setRides(Collection rides) {
        this.rides = rides;
      }
    }
    
    and Ride.java
    
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.interview-questions-tips-forum.net
    */
    
    package com.example;
    
    import java.util.Collection;
    
    public class Ride {
      private String name;
      private Capacity capacity;
      private Collection visitors;
      public Capacity getCapacity() {
        return capacity;
      }
      public void setCapacity(Capacity capacity) {
        this.capacity = capacity;
      }
      public String getName() {
        return name;
      }
      public void setName(String name) {
        this.name = name;
      }
      public Collection getVisitors() {
        return visitors;
      }
      public void setVisitors(Collection visitors) {
        this.visitors = visitors;
      }
    }
    
    In order to check whether the mapping defined in the HBM mapping XML file (as shown above) is correct without any mistakes, as I have written this file out of my own understanding of related Hibernate Mapping tags such as "bag", "one-to-many" etc. I choose to write a simple test client and test this mapping. But before doing any unit testing, I had to write a configuration XML file for creating SessionFactory using HSQLD as persistence. So following is the hibernate.cfg.xml file:
    <?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>
    
    <!--
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.interview-questions-tips-forum.net
    */
    -->
    
    
     <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">
          org.hsqldb.jdbcDriver
        </property>
        <property name="connection.url">
          jdbc:hsqldb:hsql://localhost/
        </property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
    
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
    
        <!-- SQL dialect -->
        <property name="dialect">
           org.hibernate.dialect.HSQLDialect
        </property>
    
        <!-- Enable Hibernate's automatic session context management 
        <property name="current_session_context_class">
          thread
        </property> -->
    
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
    
        <!-- Drop and re-create the database schema on startup  -->
        <property name="hbm2ddl.auto">create</property> 
    
        <mapping resource="AmusementPark-Ride.hbm.xml"/> 
     </session-factory>
    
    </hibernate-configuration>
    
    As you may note from the ablove configuration for SessionFactory I choose to create all tables in database to be created at runtime. This is just to speed up testing these mapping, instead of creating all the Table script manually. Now my test client/harness tends to be very simple and straight forward as to only create a Hibernate SessionFactory, then Open a Hibernate Session for persist operation to create a Amusement and Ride records at one time, as the cascade="persist" is present in the bag element of Amusement related mapping.
    Advertisement
    Client.java
    
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.interview-questions-tips-forum.net
    */
    
    import java.util.Collection;
    import java.util.HashSet;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    import org.apache.log4j.Logger;
    
    import com.example.Amusement;
    import com.example.Ride;
    
    public class Client {
    
        private 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 SessionFactory getSessionFactory() {
            return sessionFactory;
        }
        public static void createRecord()
        {
            System.out.println(getSessionFactory());
            Session session = getSessionFactory().openSession();
            Transaction trx = session.beginTransaction();
            trx.begin();
            Amusement ams = new Amusement();
            ams.setName("IQTF Park");
            Ride  ride1 = new Ride();
            ride1.setName("Round Fun");
            Collection colRides = new HashSet();
            colRides.add(ride1);
            ams.setRides(colRides);
            session.persist(ams);
            
            trx.commit();
            session.close();
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            createRecord();
        }
    }
    
    After running this Client, is it seen that appropriate tables are created in database, like Amusement_Park and Ride_Info with appropriate records as follows:
    Amusement_Park
    
    AP_NAME
    IQTF Park
       Ride_Info
    
    Ride_Name | Rides
    Round Fun | IQTF Park

    Commented By ->
    Guddu
    We can use list tag in place of bag tag in the HBM XML file.
    As follows:
    
      <list name="rides" cascade="persist">
        <key column="rides"/>
        <index column="list_name"/>
        <one-to-many class="Ride"/>
      </list>
    
    And the Client code should be using any collection that implements
    List , such as ArrayList, instead of the HashSet.

    Commented By ->
    Guddu
    One to many mapping relationship as shown in this example,
    replacing bag tag with set tag and this example works well.
    
    ....
    ....
          <set name="rides" cascade="persist">
            <key column="rides"/>
            <one-to-many class="Ride"/>
          </set>
    
    ....
    ....

    Commented By ->
    guddu
    For this example, by changing the bag tag with following mapping
    with list element and list-index as the sub-element with a column
    name as "list_name"  with a starting base number/index value as
    "2".
    ...
    ...
    <list name="rides" cascade="persist">
      <key column="rides"/>
      <list-index column="list_name" base="2"/>
      <one-to-many class="Ride"/>
    </list>
    ...
    ...
    
    In order to test this mapping, the client code should be
    adding more than or equals to two rides, as follows:
    
                    Amusement ams = new Amusement();
                    ams.setName("IQTF Park");
                    Ride  ride1 = new Ride();
                    ride1.setName("a Ground Fun1");
                    Ride  ride2 = new Ride();
                    ride2.setName("b Ground Fun2");
                    
                    Collection colRides = new ArrayList();
                    colRides.add(ride1);
                    colRides.add(ride2);
                    ams.setRides(colRides);
    
    Thus there will be two records in database table with
    the list_name column having auto-incremented index value
    as 2 and 3.
    
    Please write your Comment on this Matter
    (This will be visible if found suitable):
    Name: *
    Email (will not be displayed): *
    Matter: *
    28,18
    Enter bigger number from above :*
    Home > Hibernate Tutorial > Hibernate Mapping Bag > Hibernate Mapping Example
    Visitor/User submitted related resources:
    (Visible upon review and approved by this site Administrator)
    
    Referred By Name *:
    Resource URL *: (e.g, URL should be starting with http://www.-----.---)
     
    Resource Short Description *:
    10,22
    Enter bigger number from above : *

    Please log in to add or reply to any matter<- requires login
    Log in or Register
    This List is generated as on 2009-07-12 (YYYY-MM-DD)
    #Discuss-these : questions-and-answer : Interview-Questions-on-Java
    #Question-on-Session-Factory-Creation : SessionFactory : Hibernate-Tutorial
    #On-Hibernate : Interview-Questions : Hibernate-Tutorial
    #Example : mapping-class-hierarchy-table-per-subclass : Hibernate-Tutorial
    #Example : ways-create-Hibernate-SessionFactory : Hibernate-Tutorial
    #Example : Spring-Hibernate-Integration-example : Hibernate-Tutorial
    #Discussion : ORM-Hibernate-Best-FIT : Hibernate-Tutorial
    #Code : One-to-Many-mapping-example : Hibernate-Tutorial
    #code : Many-to-Many-Mapping-Example : Hibernate-Tutorial
    #discussion : Interview-questions-answer : Hibernate-Tutorial
    #example-code : Interceptor-use-log-SQL-statements : Hibernate-Tutorial
    #code : Class-Hierarchy-Persist-example : Hibernate-Tutorial
    #discussion : Case-study-Hibernate : Hibernate-Tutorial
    #With-Answer : Hibernate-Interview-Questions : Hibernate-Tutorial
    #Discussed : Hibernate-Interview-questions-answer : Hibernate-Tutorial
    #Question : Hibernate-Transaction : Hibernate-Tutorial
    #Example-Case-study : Contextual-Session : Hibernate-Tutorial
    #Design-with-example-code : Struts2-Hibernate : Hibernate-Tutorial
    #Hibernate-query : Hibernate-Criteria : Hibernate-Tutorial
    #Hibernate-Criteria-Example : Hibernate-Filter-Example : Hibernate-Tutorial
    #Hibernate-Filter-Example : Hibernate-Filter : Hibernate-Tutorial
    #Hibernate-Sample : Hibernate-many-to-one : Hibernate-Tutorial
    #Hibernate-Sample-Example : Hibernate-named-query : Hibernate-Tutorial
    #Composite-Primary-Key : Hibernate-Composite-Key : Hibernate-Tutorial
    #Mapping-Example : Hibernate-one-to-one : Hibernate-Tutorial
    Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
    CONTACT    PRIVACY POLICY    DISCLAIMER
    
    This web site provides some of the information about various technologies, example 
    code, tips, tutorials etc. Like any printed matterials, content of these pages may 
    become out of date over a period of time. Therefore all visitor/users of this web 
    site are requested/advised to refer to the originating parties/sources for the 
    latest changes and happenings for detailed information. This information is not 
    intended to be a substitute for the original reference provided by the originating 
    parties/sources.