Programmer's Blog

Programmer's reference

Category Archives: J2EE

[J2EE] Hibernate Example

Hibernate is a framework which you can map database records to java Objects/variables. So that you can use minimum code for interaction with database.

required files:

1. Hibernate configuration file (hibernate.cfg.xml)

An written example can be found here.

2. hibernate mapping file (Test.hbm.xml)

Find example here. Test is name of the the record Object

e.g. if you use Test.java for record Object, then name as Test.hbm.xml

3. Record Object Class (Test.java)

At the bottom of the above example, it just contains

constructor, getter and setters for storages of variables which

corresponds to the data of each column in the database.

4. hibernate Library 

you’ll need the following jars

mysql-connector-java-5.1.31-bin.jar
serializer.jar
xalan.jar
xercesImpl.jar
cglib-3.1.jar
commons-logging-1.1.3.jar
commons-logging-adapters-1.1.3.jar
commons-logging-api-1.1.3.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.4.Final.jar
hibernate-core-4.3.5.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar

Main Program Example  (Testing. java)

=========================================================

import java.util.List;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Testing {

   private static SessionFactory factory;

   @SuppressWarnings("depreciation")
   public static void main(String[] args) {

   try{
     factory = new Configuration().configure().buildSessionFactory();
   }catch (Throwable ex) {
     System.err.println("Cannot create sessionFactory object" + ex);
     throw new ExceptionInInitializerError(ex);
   }

   Testing TestObj = new Testing();   //object of self

   Integer record1 = TestObj.addRecord("E091",2944);  //return class type integer
   Integer record2 = TestObj.addrecord("E092",2947);

   TestObj.listRecords();
   TestObj.updateRecord(record1, 2900);
   TestObj.deleteRecord(record2);

 }

 public Integer addRecord(String inputStr, int inputInt){
   //open new factory session, transaction and return value of ID
   Session session = factory.openSession();
   Transaction tx = null;
   Integer retID = null;

 try{
   //1. begin transaction 2. create new record obj
   //3. save session 4. commit transaction
   //retID returns the generated id in DB

   tx = session.beginTransaction();
   Test recordObj = new Test(inputStr, inputInt);
   retID = (Integer) session.save(recordObj);
   tx.commit();

 } catch (HibernateException e) {
   if (tx!=null) tx.rollback();
   e.printStackTrace();
 } finally {
   session.close();
 }
   return retID;
 }

public void listRecords() {

   Session session = factory.openSession();
   Transaction tx = null;

   try{
     //Get object Testing from a query of List li
     tx = session.beginTransaction();
     List li = session.createQuery("FROM TEST").list();

     for (Iterator iterator = li.iterator(); iterator.hasNext();){

     Test recordObj = (Test) iterator.next();
     System.out.print(recordObj.getTestStr());
     System.out.println(" " + recordObj.getTestNbr());
   }

   } catch (hibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace();
   } finally {
     session.close();
   }
 }

 public void updateRecord(Integer inputID, int inputInt) {

   Session session = factory.openSession();
   Transaction tx = null;

   try{
     tx = session.beginTransaction();
     Test recordObj = (Test) session.get(Test.class, inputID);
     recordObj.setTestNbr( inputInt );
     tx.commit();

   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace();
   }finally {
     session.close();
   }

 }

public void deleteRecord(Integer inputID) {

   Session session = factory.openSession();
   Transaction tx = null;

   try{
     tx = session.beginTransaction();
     Test recordObj = (Test) session.get(Test.class, inputID);
     session.delete(inputID);
     tx.commit();

   }catch (HibernateException e) {
     if (tx!=null) tx.rollback();
     e.printStackTrace();
   }finally {
     session.close();
   }
}
} //class

 

Advertisements

[J2EE] hibernate mapping sample Test.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   //map class Test.java to database table TEST
<class name="Test" table="TEST">

   <meta attribute="class-description">
   This class contains the employee detail. 
   </meta>
   //map variable in class Test to columns in the database
   <id name="id" type="int" column="id">
     <generator class="native"/>
   </id>

   <property name="testStr" column="test_string" type="string"/>
   <property name="testNbr" column="test_number" type="int"/>

</class>
</hibernate-mapping>

<<<Extracts of class Test.java>>>
private String testStr; 
private int testNbr; 

 public Test() {}    //constructor
 public Test(String inputStr, int inputNbr) {
 this.testStr = inputStr;
 this.testNbr = inputNbr;
 }

.... getters and setters


[J2EE] Hibernate Configuration hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
 
   <property name="hibernate.dialect">
     org.hibernate.dialect.MySQLDialect
   </property>
 
   <property name="hibernate.connection.driver_class">
     com.mysql.jdbc.Driver
   </property>

   <property name="hibernate.connection.url">
     jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
     test
   </property>
   <property name="hibernate.connection.password">
     test
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Test.hbm.xml"/>

</session-factory>
</hibernate-configuration>