Home arrow Java arrow Page 4 - Introducing Hibernate

Introducing Hibernate

Databases are complex to implement. This is especially true when components of a database based on two different approaches (i.e. object oriented vs. relational) must interact with each other. Object Relational Mapping (ORM) frameworks can act as mediators between the two approaches. Hibernate, the topic of this article, is an ORM framework for Java.

Author Info:
By: A.P.Rajshekhar
Rating: 4 stars4 stars4 stars4 stars4 stars / 77
December 06, 2005
  1. · Introducing Hibernate
  2. · Object Relational Mapping: What is it?
  3. · Getting Started With Hibernate
  4. · Hibernate in the Real World

print this article

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:


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"
<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" />
<property name="date" not-null="false" >
  <column name="order_date" sql-type="datetime" not-null="true" />
<property name="priceTotal" not-null="false" >
  <column name="price_total" sql-type="double" not-null="true" />

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"
<!-- Database connection settings -->
<property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property>
<property name="connection.url">jdbc:oracle:thin:@localhost:
<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"/>

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()
        SessionFactory sf = cfg.buildSessionFactory();
        // open session
        Session sess = sf.openSession();
        // search and return
        List list = sess.find(query, id,
        if (list.size() == 0) {
            System.out.println("No Order having id "
                               + id);
        Order o = (Order) list.get(0);
        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.

blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- 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 ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials