Monday, April 15, 2013

Source code to create a simple hibernate application


This post helps you to create an application to perform basic  DB operations using hibernate framework. The intent of posting this blog is to provide working source code to perform simple DB CRUD operations. The code provided here uses Mysql database and hibernate without annotations.

Before starting with the coding part make sure that you have added required libraries to your workspace. If not please download it from websites below.
      1)     Hibernate jar location: http://sourceforge.net/projects/hibernate/files/hibernate3/3.1.3/
      2)      Add the Mysql jars depending upon the version of Mysql. I am using mysql 5. (ex: mysql-connector-java-5.1.24.jar,mysql.jar)

Steps to perform basic DB operations:
       1)      Prepare the configuration
       2)      Build the session factory from configuration
       3)      Open the session from session factory
       4)      Begin the transaction using session.
       5)      Perform DB operations
       6)      Commit the transaction
       7)      Close the session

Using the transaction is not mandatory here.But it is a good practice.

Project structure:

Create the following mappings and code.
1       1)      Create an object class (which has to be persisted).
2       2)      Create a mapping file to map between the object and DB table.
         3)      Create a configuration for hibernate.
         4)      Create a class to perform the database operations mentioned above.



    hibernate.cfg.xml :
   Add the connection properties and the other resources such as mapping files.




<?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>
   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/HibDB</property>
    <property name="connection.username">root</property>
    <property name="connection.password">pass123</property>
    <mapping resource="com\sabhahit\mapping\Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

    Student.hbm.xml :

   Add the mapping between the object and the database tables.Primary key of the table should be mentioned as part of id.

     <?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>
   <class name="com.sabhahit.objects.Student" table="Student" lazy="false">
      <meta attribute="class-description">
         This class contains the Student detail. 
      </meta>
      <id name="studentID" type="int" column="studentID">
         <generator class="increment"/>
      </id>
      <property name="name" column="name" type="string"/>
      <property name="grade" column="grade" type="string"/>
      <property name="standard" column="standard" type="int"/>
      <property name="dateOfBirth" column="dateOfBirth" type="date"/>
    </class>
   </hibernate-mapping>


    Student.java
    It is the Bean class/object which should be persisted.

      package com.sabhahit.objects;


      import java.util.Date;




      public class Student {
public Student()
{
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
private int studentID;
private String name;
private String grade;
private int standard;
private Date dateOfBirth;

public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int getStandard() {
return standard;
}
public void setStandard(int standard) {
this.standard = standard;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

     }


         BasicCRUDOperations.java

        This is the class which has methods to perform all the basic DB Operations.
         
          package com.sabhahit.utils;


import org.hibernate.HibernateException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.sabhahit.objects.Student;

public class BasicCRUDOperations {


private static SessionFactory factory;

static String INSERT ="Insert";
static String UPDATE ="Update";
  static String DELETE ="delete";
  static String READ = "select";

public static Student doCRUDOperations(Student student,String Operation)
{
Session session = null;
Transaction tx = null;
Student st = null;
try{
session = factory.openSession();
tx = session.beginTransaction();

if(Operation.equalsIgnoreCase(INSERT)){
session.save(student);
}else if(Operation.equalsIgnoreCase(UPDATE)){
session.update(student);
}else if(Operation.equalsIgnoreCase(DELETE)){
session.delete(student);
}else if(Operation.equalsIgnoreCase(READ)){
st =(Student) session.load(Student.class, new Integer(student.getStudentID()));
}

tx.commit();

return st;
}catch (HibernateException e) {
System.out.println("Exception while Performing "+ Operation);
e.printStackTrace();
tx.rollback();
return null;
}finally{
session.close();
}
}

public static void getSessionFactory()
{
Configuration cfg = new Configuration();
cfg.configure("com\\sabhahit\\databaseConfig\\hibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}
   }

           FirstHibernateApp.java

         This class uses the methods in the   BasicCRUDOperations.java to perform DB operations.

          package com.sabhahit.utils;


import java.text.ParseException;

import java.text.SimpleDateFormat;
import java.util.Date;


import com.sabhahit.objects.Student;


public class FirstHibernateApp {


public static void main(String[] args) {

BasicCRUDOperations.getSessionFactory();
 
//Create a new Student
Student st = new Student();
st.setName("Demon");
st.setStandard(1);
st.setGrade("A");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date dob;
try {
dob = sdf.parse("20/08/1978");
st.setDateOfBirth(dob);
} catch (ParseException e) {
e.printStackTrace();
}
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.INSERT);

//Update Student details
st.setName("Monster");
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.UPDATE);

//Get Student details
Student rdSt =BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.READ);
System.out.println(rdSt.getName() + rdSt.getStudentID());
//Delete Student with id=1 details
st.setStudentID(1);
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.DELETE);

}


}



     Create the student table as per below.
          


         




Now you can run the application from FirstHibernateApp class.You can see all the DB operations executing without any issues.
        
        Please share your comments if this post has helped you to create your first hibernate application.Happy learning :)


      





2 comments:

  1. hi,
    it is not a working code!
    while i executing the code am getting the following error: Error: Could not find or load main class org.apache.catalina.startup.Tomcat$1

    ReplyDelete
    Replies
    1. Hi Its not the issue with the code.But the issue with the tomact server...fix the problem using the post
      http://stackoverflow.com/questions/1392383/server-tomcat-v6-0-server-at-localhost-failed-to-start

      Delete

Resolve "Target runtime Apache Tomcat v6.0 is not defined." error

Go to window ->preferences ->Server->Runtime environments . add server Apache Tomcat v6.0 Mention the directory where apache-toma...