How to create a Hibernate Web Application (Simple example)


First of all, create a Hibernate.cfg.xml file and put it into WEB-INF/classes folder inside WAR file.
I am using derby database (bundled in Java)in this project.

<?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”&gt;
<hibernate-configuration>
  <session-factory>
    <property name=”hibernate.dialect”>org.hibernate.dialect.DerbyDialect</property>
    <property name=”hibernate.connection.driver_class”>org.apache.derby.jdbc.ClientDriver</property>
    <property name=”hibernate.connection.url”>jdbc:derby://localhost:1527/sample</property>
    <property name=”hibernate.connection.username”>app</property>
    <property name=”hibernate.connection.password”>app</property>
    <property name=”current_session_context_class”>thread</property>
     <mapping/>
  </session-factory>
</hibernate-configuration>

Create a Customer.java file

package com.tunatore.hibernateexample;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author tunatore
 */

@Entity
@Table(name = “CUSTOMER”) //reference for the table inside Database
public class Customer implements Serializable{

    @Id //Colum CUSTOMER_ID inside database will be mapped to customer_ID
    @Column(name = “CUSTOMER_ID”)
    private int customer_ID;
 //Colum NAME inside database will be mapped to customer_ID
    @Column(name = “NAME”)
    private String name;
 //Colum CITY inside database will be mapped to city
    @Column(name = “CITY”)
    private String city;
//Colum STATE inside database will be mapped to state
    @Column(name = “STATE”)
    private String state;
/**

     * @return the customer_ID
     */
    public int getCustomer_ID() {
        return customer_ID;
    }
/**
     * @param customer_ID the customer_ID to set
     */
    public void setCustomer_ID(int customer_ID) {
        this.customer_ID = customer_ID;
    }
/**

     * @return the name
     */
    public String getName() {
        return name;
    }
/**

     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
/**

     * @return the city
     */
    public String getCity() {
        return city;
    }
/**

     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }
/**

     * @return the state
     */
    public String getState() {
        return state;
    }
/**

     * @param state the state to set
     */
    public void setState(String state) {
        this.state = state;
    }

}

Create a HibernateManager.java file for getting SessionFactory object from Hibernate ORM.

package com.tunatore.hibernateexample;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateManager // Hibernate utility class
{
  private static final SessionFactory sessionFactory;

  static {    //create sessionFactory only once    
    try {
      // creating the SessionFactory from hibernate.cfg.xml            
      sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    } catch (Throwable ex) {
           System.err.println(“SessionFactory initial creation error.”+ ex);
      throw new ExceptionInInitializerError(ex);
    }
  }
  public static SessionFactory getSessionFactory() {
     return sessionFactory;
  }

}

Create a business operations class HibernateExample.java
package com.tunatore.hibernateexample;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author tunatore
 */
public class HibernateExample {

    public static Customer[] getCustomersInState(String stateName) {

    //create SessionFactory object for opening Session
SessionFactory sessionFactory  = HibernateManager.getSessionFactory();

    Session session = sessionFactory.getCurrentSession();
//Criteria requires a transaction opened
    session.beginTransaction();
    //create Criteria for Customer class
Criteria criteria = session.createCriteria(Customer.class);

//add a Restriction which will be used for equality –> state = ‘MI’
criteria.add(Restrictions.eq(“state”, stateName));
//add an order for using customer_ID column
criteria.addOrder(Order.asc(“customer_ID”));
//return the resultset as a List
List<Customer> customers = criteria.list();

//convert List to Array
    return customers.toArray(new Customer[customers.size()]);

    }
}

And last, create a index.jsp file for testing bussiness method –>getCustomersInState()

<%–
    Document   : index
    Created on : 14.June.2011, 20:29:36
    Author     : tunatore
–%>

<%@page import=”com.tunatore.hibernateexample.HibernateManager”%>
<%@page import=”org.hibernate.SessionFactory”%>
<%@page import=”com.tunatore.hibernateexample.Customer”%>
<%@page import=”com.tunatore.hibernateexample.HibernateExample”%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
        <title>Customers in State –> MI</title>
    </head>
    <body >
        <h1>Customers</h1>
        <table width=”600px” border=”1″ bgcolor=”#FFF380″>
            <tr>
                <th width=”100px”>Customer_ID</th>
                <th width=”100px”>City</th>
                <th width=”100px”>State</th>
                <th width=”100px”>Name</th>
            </tr>
            <tr>                
            <%
                Customer[] customerArr = HibernateExample.getCustomersInState(“MI”);
                for(int i=0; i < customerArr.length; i++){
            %>
            <tr>
                <td><b><%=customerArr[i].getCustomer_ID()%></b></td>
                <td><b><%=customerArr[i].getName()%></b></td>
                <td><b><%=customerArr[i].getCity()%></b></td>
                <td><b><%=customerArr[i].getState()%></b></td>                
            </tr>
            <%
                }
                HibernateManager.getSessionFactory().getCurrentSession().disconnect();
            %>               
            </tr>
        </table>
    </body>
</html>

Output of the Application


Download Project’s source (WAR file)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s