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

Talking to the Database

Let use see the simplest way to connect our Java program to MySql database. For running this program, following are required.

1) MySql Database installed.
2) MySql-Connector-Java.jar file [  to be placed in the same folder of your program ]

Inorder to make your Java program communicate with any database, remember the following points


  • Load the Driver Class [ Class.forName(" fully qualified name of the database driver  ")].
  • Get a connection object from the DriverManager providing databaseName/username/password.
  • Create statement for query using the connection object
  • Execute the query using the statement object
That's it, now let us get into the code. This code explains all the four basic operations of Database queries.
  •  Insertion /  Updation / Deletion / Selection of records from a database table.

import java.sql.DriverManager;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class JavaMysql
{


public Connection getDBConnection() throws SQLException,ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/MyDatabase","root","pass123");
 return connection;
}


public static void main(String args[])
{
JavaMysql jm = new JavaMysql();
Connection con = null;
Statement stmt = null;
ResultSet resultSet = null;
try
{
con = jm.getDBConnection();
stmt = con.createStatement();
int i=0;


// inserting a new row into student table
 System.out.println("------------------------ About to insert ------------------------");
 stmt.executeUpdate("insert into student values('Michael',1)");
 stmt.executeUpdate("insert into student values('John',2)");
 System.out.println(" 2 Rows inserted ");

 // selecting rows and printing as output
 System.out.println("------------------------ Before updation and Deletion -----------");
 resultSet = stmt.executeQuery("select * from student");
 while(resultSet.next())
 {
  i++;
 System.out.println("Row " + i + " contains " + resultSet.getString("name") + " with roll no " + resultSet.getString("rollno"));
  }

 // updating an existing row
 System.out.println("------------------------ About to update ------------------------");
 int no_of_rows_updated = stmt.executeUpdate("update student set rollno=10 where rollno=2 ");
 System.out.println("No of rows updated are " + no_of_rows_updated);


 // deleting a row
 System.out.println("------------------------ About to delete ------------------------");
 int no_of_rows_deleted = stmt.executeUpdate("delete from student where rollno=1");
 System.out.println("No os rows deleted are " + no_of_rows_deleted);

 // viewing the output again
 System.out.println("------------------------ After updation and Deletion ------------");
 resultSet = stmt.executeQuery("select * from student");
 i=0;
       
 while(resultSet.next())
{
i++;
System.out.println("Row " + i + " contains " + resultSet.getString("name") + " with roll no " + resultSet.getString("rollno"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Please note :
you must use different functions to perform different operations

1) executeUpdate - insert,delete,update
2) executeQuery - select

Kick start some of the J2EE Technologies

Hello Techies,

Are you interested in learning new Technologies in Java? I will keep you posted on some of the Technologies in Java/J2EE i know. If you find it useful, please subscribe to my blog and get regular updates and also dont forget to leave your vote.

Bhaskara Vignesh.c

Was this Blog Helpful?