Advertisement :
   Log In    OR    Register  
  Topics :  
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 : 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...


Written By : Amit
Title :
ORM Hibernate Best FIT
Description : Discussion
More...


Written By : Amit
Title :
One to Many mapping example
Description : Code
More...


Written By : Amit
Title :
Many to Many Mapping Example
Description : code
More...


Written By : Amit
Title :
Interview questions answer
Description : discussion
More...

Tags/Keywords : Hibernate Mapping, Hibernate, Mapping, Bag,element , Code, Tutorial, Article
Author : guddu
Date (Year/Month/Date): 2009-12-06 Hibernate-Mapping-Bag Element example

Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this 
as it is without appropriate evaluation to their, so to say, 
specific programming context.

This page intends only to provide bit and piece of known ways  for
doing some sort of example and may not be fit for any other purpose.

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.
    
    Are you interested in solving a very interesting Technology Stack while Playing this Game          

    Please write your Comment on this Matter
    (This will be visible if found suitable):
    Name: *
    Email (will not be displayed): *
    Matter: *
    4,6
    Enter bigger number from above :*
    Home >>> Hibernate Tutorial >>> Hibernate Mapping Bag >>> Hibernate Mapping Example
    Visitor/User referred related external URL:
    (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 *:
    3,16
    Enter bigger number from above : *

    Please log in to add or reply to any matter<- requires login
    Log in or Register
    Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
    CONTACT    PRIVACY POLICY    DISCLAIMER
    Terms of Use and Disclaimer :
    
    This web site provides some of the information about various technologies, example 
    code, tips, tutorials etc. Like any printed materials, 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.
    
    By accessing and using this website in any ways, including, without
    limitation, browsing the website pages, using any information, using any content and/or 
    downloading any materials, you agree to and are bound by the terms of use 
    described in this page and Usage Terms and Conditions. 
    If you do not agree to all of 
    the terms and conditions contained in the terms of use described in this
    page and Usage Terms and Conditions, do not use this 
    website in any manner. If you are using the website on behalf of your 
    employer, you represent that you are authorized to accept these Terms of Use 
    on your employer's behalf.
    
    All Trademarks are property of their respective owner. Appropriate measure is being
    taken for providing accurate and up-to-date information but like any printed materials,
    these blog(s)/contents may eventually be outdated one day, so if you are using any 
    of these information, please refer original content/documentation from respective sources. 
    And under no circumstances shall the Author of these contents and/or this web site
    be liable for any loss, damage, expense incurred or suffered which is claimed to have
    occurred because of usage of the contents of this web site.
    If you have any questions/queries/feedback/suggestions then please write to this web
    site owner at contact.