Talking to Database Using Hibernate Framework

I hope you have gone through the previous post- "Talking to the Database". That was a very basic , but classical way of connecting to the database. In this post let us see the Database communication using Hibernate Framework. Its one of the widely used Framework in Java Enterprise.
Hibernate simply means Object-->Relational Mapping. 


  1. We create tables in database
  2. We create Classes to identify an object in Java [POJO] 
  3. Finally we create a link between the database table and Java class in an xml file
  4. Provide database parameters in another xml
Everything else is taken care by Hibernate. All you will have to worry about is some hibernate methods to do the INSERT/UPDATE/DELETE/SELECT operations which are very simple.


Make sure you have these Jar files before continuing..



  1. hibernate3.jar
  2. dom4j.jar
  3. log4j.jar
  4. commons-logging.jar
  5. commons-collections.jar
  6. mysql-connector-java-5.1.6.jar
  7. cglib.jar
  8. asm.jar
  9. jta.jar
  10. antlr.jar

Place all the files in E:/JavaPrograms/Hibernate folder, including the one you written below




import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.ArrayList;
import java.io.DataInputStream;


public class JavaHibernate
{
static Session session;
static Transaction tx;
                               
public static void main(String args[])
{


boolean option = true;
try
{
do
{
                System.out.println("1 - Add Student");
                System.out.println("2 - Update Student");
                System.out.println("3 - Delete Student");
                System.out.println("4 - View Student");
                System.out.println("5 - Exit");
                System.out.println("Enter your choice ....");




                DataInputStream dis = new DataInputStream(System.in);
                int opt = Integer.parseInt(dis.readLine());
                switch(opt)
                {
                      case 1:
                     {
                        System.out.println("Enter the student's name :");
                        String name = dis.readLine();
                        addStudent(name);
                        selectAllStudents();
                        break;
                      }
                      case 2:
                      {
                         System.out.println("Enter the rollno of student who has to be updated :");
                         int rollno = Integer.parseInt(dis.readLine());
                         System.out.println("Enter his new Name :");
                         String name = dis.readLine();
                         updateStudent(name,rollno);
                         selectAllStudents();
                         break;
                        }
                       case 3:
                        {
                           System.out.println("Enter the student's rollno :");
                           int rollno = Integer.parseInt(dis.readLine());
                           deleteStudent(rollno);
                           selectAllStudents();
                           break;
                         }
                         case 4:
                        {
                          System.out.println("Enter the rollno of the student to be viewed :");
                          int rollno = Integer.parseInt(dis.readLine());
                          viewStudent(rollno);
                          break;
                         }
                         case 5:
                         {
                            option=false;
                            break;
                          }
                          default:
                          {
                              System.out.println("Enter correct option");
                           }              
            
                }
}while(option);
               
}
catch (Exception e)
{
          e.printStackTrace();



}


public static void startSession()
{
session = InitSessionFactory.getSession();
tx = session.beginTransaction();       
}
  
// inserting a new student
public static void addStudent(String name)
{
startSession();
Student s = new Student();
s.setName(name);
//s.setRollno(10);   need not set roll no as it is unique and defined to be auto-incremented in hbm.xml file
session.save(s);
tx.commit();
System.out.println("Student added ");
}


// updating an existing student
public static void updateStudent(String name,int rollno)
{
startSession();
Student existingStudent = (Student)session.get(Student.class,rollno);
if(existingStudent!=null)
{
String oldName =  existingStudent.getName();
existingStudent.setName(name);
session.saveOrUpdate(existingStudent);
String newName = existingStudent.getName();
System.out.println(oldName + " updated to " + newName);
}
tx.commit();
}


// deleting a new student
public static void deleteStudent(int rollno)
{
startSession();
Student deleteStudent = (Student)session.get(Student.class,rollno);
if(deleteStudent!=null)
{
String name = deleteStudent.getName();
session.delete(deleteStudent);
System.out.println(name + " is now deleted");
}
tx.commit();
}


// iterating through a student's record
public static void viewStudent(int rollno)
{
startSession();
Student oldStudent = (Student)session.get(Student.class,rollno);
if(oldStudent!=null)
{
System.out.println(oldStudent.getName() + "'s rollno is " + oldStudent.getRollno());
}
}


public static void selectAllStudents()
{
startSession();
String query = "from Student";
ArrayList studentList = (ArrayList)session.createQuery(query).list();
System.out.println("-----------------------------------------------------");
for(Student s : studentList)
{
                System.out.println(s.getName() +"'s roll no is "+ s.getRollno());
}
System.out.println("-----------------------------------------------------");
}




}


comand to compile


 E:/JavaPrograms/Hibernate>javac -cp E:/JavaPrograms/Hibernate/hibernate3.jar;E:/JavaPrograms/Hibernate  JavaHibernate.java


command to run


E:/JavaPrograms/Hibernate>java -cp E:/JavaPrograms/Hibernate/hibernate3.jar;E:/JavaPrograms/Hibernate/dom4j.jar;E:/JavaPrograms/Hibernate/log4j.jar;E:/JavaPrograms/Hibernate/commons-logging.jar;E:/JavaPrograms/Hibernate/commons-collections.jar;E:/JavaPrograms/Hibernate/mysql-connector-java-5.1.6.jar;E:/JavaPrograms/Hibernate/cglib.jar;E:/JavaPrograms/Hibernate/asm.jar;E:/JavaPrograms/Hibernate/jta.jar;E:/JavaPrograms/Hibernate/antlr.jar;E:/JavaPrograms/Hibernate  JavaHibernate

1 comment:

Was this Blog Helpful?