Saturday 27 August 2011

Hibernate Basic Example for Learning Hibernate.........



Process.java

package com;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Process
{
    static Session session=null;
   
    public static void main(String[] args)
    {
        try
        {
            selectAll();
             System.out.println("Done");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void insert(String name)
    {
        session = HibernateUtil.getSessionFactory().openSession();
         EmpBean empBean=new EmpBean();
         System.out.println("Inserting Record");
         session.beginTransaction();
       
         empBean.setName(name);
       
         session.save(empBean);
         session.getTransaction().commit();
         HibernateUtil.getSessionFactory().close();
    }
    public static void selectAll()
    {
        session = HibernateUtil.getSessionFactory().openSession();
        Query query=session.createQuery("from EmpBean"); // EmpBean is a Class name which is created..
        List rs=query.list();
        for(int i=0;i<rs.size();i++)
        {
            EmpBean e=(EmpBean) rs.get(i);
            System.out.println("Name  :" +e.getName());
            System.out.println("Id  :" +e.getId());

        }
        HibernateUtil.getSessionFactory().close();
    }

}

HibernateUtil.java

package com;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil
{
    private static final SessionFactory sessionFactory = buildSessionFactory();
   
    private static SessionFactory buildSessionFactory()
    {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration config=new Configuration().addResource("hibernate.cfg.xml"); 
// hibernate.cfg.xml is hibernate cofiguration file you can give your xml file..
            return config.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;
    }
}

EmpBean.java

package com;

public class EmpBean
{
    private Long id=new Long(10);;
    private String name;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }   

}

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//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:oracle</property>
        <property name="connection.username">jatin</property>
        <property name="connection.password">jatin</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>
        <!-- dialect for common query generate by Hibernate -->
        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="hibernate.cache.use_query_cache">false</property>
       
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Mapping files -->
        <mapping resource="EmpBean.hbm.xml"/>
          <!-- EmpBean.hbm.xml is file for EmpBean class , give any name... -->
    </session-factory>
</hibernate-configuration>

EmpBean.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="com.EmpBean" table="EMPLOYEE" dynamic-update="true" dynamic-insert="true">
        <cache usage="read-write"/>
         <id name="id" column="EMPID" type="java.lang.Long">
            <generator class="increment" ></generator>
        </id>
      
       
        <property name="name" type="java.lang.String" update="true" insert="true" access="property" column="EMPNAME"/>
    </class>
</hibernate-mapping>


index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>Hibernate Page</title>
   
  </head>
 
  <body>
  <form action="insert.jsp" >
    <table>
        <tr>
            <td>Emp Name : </td>
            <td><input type="text" name="empname"></td>
        </tr>
        <tr>
            <td><input type="submit" value="Insert" name="submit">
                <input type="reset" value="cancel" name="reset">
            </td>
        </tr>
    </table>
    </form>
  </body>
</html>

insert.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="com.Process;"%>


<%
new Process().insert(request.getParameter("empname"));
request.getRequestDispatcher("index.jsp").forward(request,response);
%>
List of Jar which is needed for run this example
hibernate.jar
ojdbc14.jar

Wednesday 10 August 2011

Welcome

Hi,

I am Jatin Kansagara working as a Juniour Java Developer at Spec-India, Ahmedaba since January 2011.