Translate

Thursday, 28 November 2013

Learn Hibernate Quick

Before we proceed with Hibernate it is important to understand 2 basic concepts: ORM and RDBMS.
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc.
Examples of ORM:

  • Hibernate
  • TopLink
  • Castor

RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C# represent it as an interconnected graph of objects.
                Hibernate is an ORM created by Gavin King in 2001. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. Hibernate works best with POJO.
                Hibernate is a popular framework with many advantages over traditional RDBMSs. Few of the important ones are listed below:
Advantages of Hibernate include:

  1. Fast development of application
  2. Hides details of SQL queries from OO logic
  3. No need to deal with the database implementation.
  4. Takes care of Transaction management.

    Hibernate Architecture

JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Configuration Object
The Configuration object provides two keys components:
Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml(an example file is given below).

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

<!-- Assume test is the database name -->
      <property name="hibernate.connection.url">
         jdbc:mysql://localhost/test
      </property>
      <property name="hibernate.connection.username">
         root
      </property>
      <property name="hibernate.connection.password">
         root
      </property>

<!-- List of XML mapping files -->
      <mapping resource="Employee.hbm.xml"/>
   </session-factory>
</hibernate-configuration>
-------------------------------------------------------------------------------------------------------------------------

Class Mapping Setup
This component creates the connection between the Java classes and database tables..

SessionFactory Object
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. One SessionFactory object per database using a separate configuration file is made. So while using multiple databases multiple SessionFactory objects need to be created.

Session Object
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. It must be opened and closed as the requirement, should not be kept open for a long time as it is not thread safe.

Query Object
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Hibernate Mapping
This is where the classes are mapped onto tables of databases.
A Hibernate mapping file usually has the name: <name-of-the-class-to-be-mapped>.hbm.xml
The contents of a hibernate mapping file generally look like this:

<hibernate-mapping>
   <class name="Employee" table="OFFICEEMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail.
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

Here the class being mapped is Employee to a table named OFFICEEMPLOYEE.
We then start mapping class variables to the table columns. The name of this file should be Employee.hbm.xml

Application Class (has main method to use the hibernate setup we just created)
General structure of code in main method of application class
------------------------------------------------------------------------------------------------------------------------
Session session = factory.openSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();
   // do some work...
   tx.commit();
}
catch (Exception e) {
   if (tx!=null) tx.rollback();
   e.printStackTrace();
}finally {
   session.close();
}
---------------------------------------------For more info. about Session interface refer this Link.----
               
               
----Follow the code below to create the factory Object from Configuration object.---------------
try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) {
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex);
      }
-------------------------------------------------------------------------------------------------------------------------

-------------TO MAKE AN ENTRY FOR A NEW EMPLOYEE---------------------------------------
Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee);
         tx.commit();
      }
    catch (HibernateException e) {
         if (tx!=null){
             tx.rollback();       
         }
         e.printStackTrace();
      }finally {
         session.close();
      }
-------------------------------------------------------------------------------------------------------------------------

----------TO READ ALL THE EMPLOYEES--------------------------------------------------------------
Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list();
         for (Iterator iterator = employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next();
            System.out.print("First Name: " + employee.getFirstName());
            System.out.print("  Last Name: " + employee.getLastName());
            System.out.println("  Salary: " + employee.getSalary());
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
------------------------------------------------------------------------------------------------------------------------

----------Using Hibernate 3.0 with Annotations-------------------------------------------------------------
above class name
    @Entity
    @Table(name="OFFICEEMPLOYEE")

above class variables name
    @Column(name="id")
    @GeneratedValue
    @Id

Only the factory object needs to be altered in case of using annotations, rest all remains the same
factory = new AnnotationConfiguration().configure().
               //addPackage("com.xyz") //add package if used.
               addAnnotatedClass(Employee.class).
               buildSessionFactory();

------------------------------------------------------------------------------------------------------------------------
HQL (Hibernate Query Language)
lets see some examples to understand hibernate query language.
eg1:    String hql = "SELECT E.firstName FROM Employee E";
It should be noted here that Employee.firstName is a property of Employee object rather than a field of the OFFICEEMPLOYEE table.

eg2:     String hql = "UPDATE Employee set salary = :salary " + "WHERE id = :employee_id";
            Query query = session.createQuery(hql);
            query.setParameter("salary", 1000);
            query.setParameter("employee_id", 10);
            int result = query.executeUpdate();
--------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment