Java
  Home arrow Java arrow Page 4 - Introducing Hibernate
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Introducing Hibernate
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 40
    2005-12-06

    Table of Contents:
  • Introducing Hibernate
  • Object Relational Mapping: What is it?
  • Getting Started With Hibernate
  • Hibernate in the Real World

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Introducing Hibernate - Hibernate in the Real World


    (Page 4 of 4 )

    Now that all the required introductions are over, we can get into a real world example. The requirement is to retrieve data from the Orders table. The SQL statement required to set up the table is:

    CREATE TABLE ORDERS(
            ID VARCHAR NOT NULL PRIMARY KEY,
            ORDER_DATE TIMESTAMP NOT NULL,
            PRICE_TOTAL DOUBLE NOT NULL);

    The next step is to create the persistence class:

    package com.someorg.persist;
     
    import java.util.Date;
    import java.util.HashSet;
    import java.util.Set;
     
     public class Order {
        private String id;
        private Date date;
        private double priceTotal;
           
        // Automatically set the creation time of
        // this Order
        public Order() {
            this.date = new Date();
        }
     
        public String getId() {
            return id;
        }
        public void setId(String string) {
            id = string;
        }
        // other getters/setters not shown for
        // brevity
        // ...
    }

    It is obvious from the above code that the persistence class is just a JavaBean. Next, the hbm file is created. Here is the hbm file. The name of the file is Order.hbm.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-mapping default-cascade="none" default-access="property" auto-import="true">
     
     <class name=" com.someorg.persist.Order" table="orders" mutable="true" select- before-update="false" optimistic-lock="version">
     
    <id name="id" type="string" unsaved-value="null">
      <column name="id" sql-type="char(32)" not-null="true" />
      <generator class="assigned" />
      </id>
    <property name="date" not-null="false" >
      <column name="order_date" sql-type="datetime" not-null="true" />
      </property>
    <property name="priceTotal" not-null="false" >
      <column name="price_total" sql-type="double" not-null="true" />
      </property>
     
       </class>
      </hibernate-mapping>

    All the instance variables have been mapped using the property element. Now it is time for the configuration 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>
    <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property>
    <property name="connection.url">jdbc:oracle:thin:@localhost:
    1521:orcl
    </property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="dialect"> org.hibernate.dialect.OracleDialect </property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    <mapping resource=" com/someorg/persist/Event.hbm.xml"/>
    </session-factory>
    </hibernate-configuration>

    It declares that this application will be connecting to the Oracle database. All other parameters are set accordingly, and are self explanatory.

    Now it is time to test our setup.

    package test;
    import java.util.List;
    import org.hibernate.Hibernate;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import com.someorg.persist.Order;
    // use as
    // java test. FindOrderById name
    public class FindOrderById {
     
        public static void main(String[] args) throws Exception {
            // query to issue
            String query =
                "select order from Order "
                 + "where order.id=:id";
     
            // search for what?
            String name = args[0];
     
            // init
            Configuration cfg = new Configuration()
                               .addClass(Order.class);
     
            SessionFactory sf = cfg.buildSessionFactory();
     
            // open session
            Session sess = sf.openSession();
           
            // search and return
            List list = sess.find(query, id,
                                  Hibernate.STRING);
     
            if (list.size() == 0) {
                System.out.println("No Order having id "
                                   + id);
                System.exit(0);
            }
            Order o = (Order) list.get(0);
            sess.close();
            System.out.println("Found Order: " + p);
        }
    }

    This class retrieves the Order corresponding to the id provided. First it builds a configuration based on the class name. Then SessionFactory’s instance is created from the instance of Configuration. Then a new Session is opened using the openSession() method of the SessionFactory instance. Then the find method of Session is used to retrieve the object corresponding to the id. The zeroth element of the List instance gives the object. This object is the representation of the row corresponding to the id.

    That brings us to the end of the first part of this series. In this part I have left many questions unanswered including the architecture of Hibernate and the core classes of the Hibernate. These will be covered in the next part. Until next time. 


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · HiWorking with databases is a complex thing if not hard. That is where ORM...
       · simple and easy. Nice work. thanks for the tutorial.
       · Hi Rajashekar, This is very good article about the Hibernate Frame work for me as...
       · hi rajshekar,really good and koolthanks dude
       · hi,i am a trainer working for CMC Limited. i was hunting for some basic idea...
     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    Stay green...Green IT