Data Types,  Database,  Java

RDMS interaction with Hibernate

Hibernate Object Relational Mapping (ORM) is an open source framework that facilitates Java program access and data persistence to a relational database management system.

Hibernate is an implementation of JPA and can either use XML configuration or JPA annotations to interact with a database.

Hibernate can be used in any Java application (JSP, Spring, etc). Data is represented as simple Java objects or POJOs and a session manager is used to interact with these objects. Hibernate hides the details of the database schema enabling you to focus on implementing the business logic.

The Hibernate Framework

Advantages

  1. Handles mapping objects to tables using XML configuration or JPA annotations
  2. Provides simple APIs to store and retrieve data
  3. Database changes only require changes to the XML
  4. Manages complex table associations
  5. Implicit transaction management
  6. Reduces database access using smart fetching strategies
  7. Supports caching for better performance
  8. Supports most major relational databases (HQL, DB2/NT, MySQL, Oracle, MS SQL, etc)

How does hibernate work?

1. Database access is achieved through mapping and configuration

A configuration file hibernate.cfg.xml is used to define database properties. An example of a configuration that communicates to a local instance of MySQL would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="localdatabase">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">########</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:8889/database</property>
  <property name="hibernate.connection.username">########</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 </session-factory
</hibernate-configuration>

2. Session management

Sessions are used to establish a connection to the database where core hibernate classes are used to manage any interaction. To maintain data integrity, initiate a connection only when required and close the connection as soon as possible.

Generally an application will only have a single SessionFactory instance and any threads service and client requests obtain session instances from this factory. A configuration object is used to create a SessionFactory object which will configure hibernate for the application using the supplied configuration file and allows for a session object to be instantiated.

The SessionFactory is a thread safe object that is created during application startup. Separate SessionFactory objects are required for multiple database connections.

A session object is used to get a connection to the database and is designed to be instantiated each time an interaction is required. Persistent objects are saved and retrieved through a session object. The session object wraps the underlying JDBC resources for CRUD functionality.

Transaction are used to contain a unit of work that restricts access from other users. A transaction behaves as if you have exclusive use of the database. A transaction can be started, committed or rolled back to remove all changes in the event of any connection or infrastructure failures. Transactions are handled by a Transaction Manager.

SessionFactory factory = metadata.getSessionFactoryBuilder().builder();
Session session = factory.openSession();
Transaction t = session.beginTransaction();

session.save(persistentObj);
     t.commit();
factory.close();
     session.close();

3. Mapping strategies

Entities and classes refer to tables in the database in the context of Hibernate. An instance of a class refers to a row in the table and the attributes/properties of a class refer to the columns in the table. These classes should follow the JavaBean programming model which includes getter/setter methods for all the attributes as well as a default constructor.

Mapping files must be saved with {classname}.hbm.xml.

The root element is <hibernate-mapping> and contains the <class> elements.

The <meta> tag is optional and can be used to describe a class.

The <id> element maps the unique ID attribute.

The <generator> tag is used to auto-generate primary keys.

The <property> tag is used to map a class property to a column in the table.

4. Hibernate supports reverse engineering

Reverse engineering in this context refers to a process of using the database and its existing tables to generate mapping files and POJOs. The default strategy uses a collection of rules for mapping the JDBC artifact names to the Java artifact names or the database tables to the Java classes. The mapping file (hibernate.reveng.xml) can specify type mappings and table filtering. Mapping files can be created manually or with a Hibernate plug-in.

The tag <schema-selection> is used to identify the schema(s).

The tags <table> and <table-filter> identifies tables to reverse engineer.

The <type-mapping> section is used to convert data types:

Mapping TypeJava TypeSQL Type
integerintINTEGER
shortshortSMALLINT
floatfloatFLOAT
stringStringVARCHAR

5. Hibernate includes query and retrieval operations

Query example

public class QueryExample {

    private static SessionFactory factory;
    private static ServiceRegistry registry;

    public static void main(String[] args) {
        try{
           // factory = new Configuration().configure().buildSessionFactory();
            Configuration configuration = new Configuration().configure();
            registry = new StandardServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).build();
            factory = configuration.buildSessionFactory(registry);
        }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
        
        //HQL Examples
        Session session = factory.openSession();
        //Transaction tx = null;
      
      try{
         //tx = session.beginTransaction();
		 Query query = session.createQuery("from Employee as e where e.firstName "
		 	 	 + "like 'S%' and salary > 10000");
		 List employees = query.list();
         for (Iterator iterator = 
                         employees.iterator(); iterator.hasNext();){
       /*     Employee ee = (Employee) iterator.next(); 
            System.out.print("First Name: " + ee.getFirstName()); 
            System.out.print("  Last Name: " + ee.getLastName()); 
            System.out.println("  Salary: " + ee.getSalary()); 
        */    }
         
         
      }catch (HibernateException e) {
        // if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
        
    
        StandardServiceRegistryBuilder.destroy(registry);
    
    }
    
}

The hibernate session interface contains several create criteria API methods that is used to restrict results from a query. Multiple criteria can be concatenated to build on a filter on the result set.

...
   try {
        criteria criteria = session.createCriteria(product.class);
        criteria.add(Restrictions.gt("price", 1000));
        Criteria.addOrder(Order.asc("productName"));
        list products = criteria.list();
   ...

   } catch (HibernateException e) {
       e.printStackTrace();
   } finally {
       session.close();
   }

6. Query results are objects instead of SQL result sets

Hibernate understand native SQL but provides an alternative query language called Hibernate Query Language (HQL) which is an object-oriented version of SQL. HQL adds a layer of abstraction for the programmer ensuring that the program would not have to change if the underlying database structure change.

HQL works with persistent objects and their properties. Queries are translated into convential SQL queries which will perform the necessary actions on the database. The preference is to use HQL over SQL to avoid any portability issues and to make use of hibernate’s SQL generation and caching features.

7. Persistence is achieved by mapping objects to tables

Hibernate works with the existing Java object model where required objects are marked as persistent. Only objects with instance variables can be stored and can be in 3 states of persistence.

Transient StatePersistent StateDetached State
Objects exist in memoryOnce saved, data becomes persistentObjects that exist in the database but a connection is lost
The database has no knowledge of the objectThe object will exist in the databaseA persistent object whose session has been closed
If the session is configured to save the data, an identifier is assignedAny change will be reflected in the current transactionThe object can be re-attached to a hibernate session if required

8. CRUD operations

When Create, Read, Update & Delete (CRUD) operations is required on the data entities, the following SQL keywords in a Data Access Object (DAO) class will implement the required operation.

OperationSQL
CreateINSERT
ReadSELECT
UpdateUPDATE
DeleteDELETE

Leave a Reply

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