Pitch your project

Random text






Blogs

0    
By admin Category Uncategorized, Posted March 21st, 2016
Hibernate ORM

Hibernate, known as the best and dominated object relational Mapper/persistence framework (ORM) tool for Java developers, in other words, a framework for mapping an object-oriented domain model to a relational database. It provides elegant and innovative ways to simplify the relational database handling task in Java.

The map Java classes to database tables is implemented by the configuration of an XML file or by using Java Annotations. For example

You have your POJO Plain Old Java Objects

public class Student {
   private int id;
   private String firstName;
   private String lastName;
   private int student_number;

   public Student() {}
   public Student(String fname, String lname, int std_num) {
      this.firstName = fname;
      this.lastName = lname;
      this.student_number = std_num;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getStudent_number() {
      return student_number;
   }
   public void setStudent_number( int student_number ) {
      this.student_number = student_number;
   }
}

Then in your database of choice, create tables of which there would be one table corresponding to each object you are willing to provide persistence, e.g.

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   student_number Int(20) default NULL,
   PRIMARY KEY (id)
);

Now create your Mapping configuration File (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>
   <class name="Student" table="STUDENT">
      <meta attribute="class-description"/>
         This class contains the student detail.

      <id name="id" type="int" column="id">
         <generator class="native"></generator>
      </id>
      <property name="firstName" column="first_name" type="string"></property>
      <property name="lastName" column="last_name" type="string"></property>
      <property name="studentnumber" column="student_number" type="int"></property>
   </class>
</hibernate>

You should save the mapping document in a file with the format .hbm.xml. We saved our mapping document in the file Student.hbm.xml.

The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

The <id> element maps the unique ID attribute in class to the primary key of the database table.

The name attribute of the id element refers to the property in the class.

The column attribute refers to the column in the database table.

The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

After creating the mapping configuration file, you will create a java file and apply CRUD operations on the records, e.g.

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 ManageStudent {
   private static SessionFactory factory;
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) {
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex);
      }
      ManageStudent MS = new ManageStudent();

      /* Add few student records in database */
      Integer stdID1 = MS.addStudent("Mike", "Jackson", 675535);
      Integer stdID2 = MS.addStudent("Muhammed", "Ali", 930245);
      Integer stdID3 = MS.addStudent("John", "Wick", 001457);

      /* List down all the students */
      MS.listStudents();

      /* Update student's records */
      MS.updateStudent(stdID1, 5000);

      /* Delete an student from the database */
      MS.deleteStudent(stdID2);

      /* List down new list of the students */
      MS.listStudents();
   }
   /* Method to CREATE an student in the database */
   public Integer addStudent(String fname, String lname){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer studentID = null;
      try{
         tx = session.beginTransaction();
         Student student = new Student(fname, lname);
         studentID = (Integer) session.save(student);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
      return studentID;
   }
   /* Method to  READ all the students */
   public void listStudents( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List students = session.createQuery("FROM Student").list();
         for (Iterator iterator =
                           students.iterator(); iterator.hasNext();){
            Student student = (Student) iterator.next();
            System.out.print("First Name: " + student.getFirstName());
            System.out.print("  Last Name: " + student.getLastName());
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
   /* Method to UPDATE student_number for an student */
   public void updateStudent(Integer StudentID, String first_name, String last_name int student_number ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Student student =
                    (Student)session.get(Student.class, StudentID);
         student.setStudent_number( student_number );
         session.update(student);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
   /* Method to DELETE an student from the records */
   public void deleteStudent(Integer StudentID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Student student =
                   (Student)session.get(Student.class, StudentID);
         session.delete(student);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
}

You should be aware that there are many ORM frameworks available, like Ebeans and its all up to you to pick on the one that suites your coding skills and requirements, have fun ‘persisting’.

Posted by Michael Mathenge

Leave a Reply

Your email address will not be published. Required fields are marked *