Tech I Enjoy Logo

Custom Search




  Home >> Hibernate

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:

  • IDE (Integrated Development Environment)- Eclipse version 3.2 -
  • Java Platform version "1.6.0_17" -
  • Hibernate version 3.2 -
  • HSQLDB version 1.8.0 -
  • Once all these software environment is set in the Development Environment. Then comes the time to create appropriate Eclipse example workspace and by creating all the folder structures and files, including Java, XML mapping and Database objects, along with SQL statements in a text 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 this examples of using Hibernate to follow: Example case study: In an amusement park, there are many rides, and each ride could have 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 of this example using a very abstract Class Relationship Collaboration format: 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.techienjoy.com
    */
    -->
    
    
    <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.techienjoy.com
    */
    
    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.techienjoy.com
    */
    
    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 based on 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.techienjoy.com
    */
    -->
    
    
     <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 might have noted from the above configuration for SessionFactory I choose to create all tables in database at runtime only. 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. Client.java
    
    /**
    * This code is provide on "AS IS" basis.
    * Copyright: Guddu
    * Source: http://www.techienjoy.com
    */
    
    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
    If anything missed out , please let me know at techienjoy at yahoo . com
    Hibernate Insert Update control :
    Hibernate Example on controlling
    insert and update attributes
    Class Hierarchy Mapping Example :
    class hierarchy mapping example using Hibernate
    Framework and a simple to follow steps.
    Example on persisting Class Hierarchy :
    Example on using Hibernate Framework
    to persist Class Hierarchy into database.
    Hibernate Join Example :
    Using Table join explained with an example
    while using Hibernate Framework.
    Hibernate Transaction on JBoss :
    Explaining Transaction using Hibernate
    on JBoss Application Server.
    Hibernate class heirarchy mapping :
    Hibernate Example on mapping
    class hierarchy using various ways
    of persisting into database
    tables.
    Hibernate Example on Filter :
    Example on using Filter using Hibernate Framework
    to work with.
    Hibernate Component Property :
    Hibernate Example on Component 
    with source code explained.
    Hibernate one to one mapping Example :
    one to one mapping explained using an example
    and Hibernate Framework.
    Hibernate Interceptor Example :
    Example on using Interceptor using Hibernate Framework
    with source code explained.
    Hibernate one to many mapping Example :
    one to many mapping explained using an example
    and Hibernate Framework.
    Hibernate Example on composite Primary key :
    Example on using Hibernate Framework
    to work with mapping using composite
    Primary key.
    Hibernate Bag Mapping Example :
    class mapping using Bag Tag example using Hibernate
    Framework and a simple to follow steps.
    List of Examples on Hibernate :
    List of example using Hibernate.
    Hibernate Example on Filter Criteria :
    Example on using Filter Criteria
    using Hibernate Framework to work with.
    Hibernate Interview Questions :
    Interview Questions on Hibernate with answer.
    Hibernate Named Query Example :
    Named Query markup using an example
    and Hibernate Framework.
    Hibernate Many to Many Mapping Example :
    Many to many mapping example using Hibernate
    Framework and a simple to follow steps.
    Hibernate Property Formula :
    Hibernate Example on Property
    Tag with ease to do code walk-through
    Hibernate one to many mapping Example :
    one to many mapping explained using an example
    and Hibernate Framework.


    References :
    Tags: Hibernate Class Hierarchy Persist example
    Tags: Hibernate composite primary key
    Tags: Hibernate criteria filter example
    Tags: Hibernate Filter Example
    Tags: Hibernate Interceptor example
    Tags: Hibernate Interview Questions
    Tags: Hibernate join example
    Tags: Hibernate Many to Many Mapping Example
    Tags: Hibernate mapping bag
    Tags: Hibernate mapping class hierarchy table per subclass
    Tags: Hibernate named query markup
    Tags: Hibernate One to Many mapping example
    Tags: Hibernate One To One Mapping Example
    Tags: Hibernate scenario one to many
    Tags: Hibernate transaction jboss
    Tags: Hibernate
    

    
    
    DISCLAIMER :
    The content provided in this page is not warranted and/or guaranteed by techienjoy.com. 
    techienjoy.com is not liable for any negative consequences that may result/arise from 
    implementing directly/indirectly any information covered in these pages/articles/tutorials.
    
    All contents of this site is/are written and provided on an "AS IS" basis,
    without WARRANTIES or conditions of any kind, either express or implied, including, without
    limitation, merchantability, or fitness for a particular purpose. You are solely responsible
    for determining the appropriateness of using or refering this and assume any risks associated
    with this.
    
    In spite of all precautions taken to avoid any typo in these pages, there might be some 
    issues like grammatical mistakes and typos being observed in these pages, techienjoy.com
    extends sincerest apologies to all our visitors for the same.
    
    
    

    Android Examples || Android Examples

    © Copyright 2010-2012, TECHIENJOY, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions