Wednesday, June 26, 2013

Hibernate


Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns.



Here with journal terms :



What you can imagine is probably that you have your application with some functions (business logic) and you want to save data in a database. When you use Java all the business logic normally works with objects of different class types. Your database tables are not at all objects.



Hibernate provides a solution to map database tables to a class. It copies the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables.

Saving data to a storage is called persistence. And the copying of tables to objects and vice versa is called object relational mapping.


Why we need to use ORM?


Better system architecture :




When you include all functionality of your application and the access to the database within your dialog s, you will have some severe disadvantages.



It is really difficult to reuse code. You will repeat code at many places. If you change anything it is quite hard to find out all places where you have to add changes.



When you separate your dialog's from your logic and the logic from the persistence mechanism you can more easily apply changes to one part without influencing the other parts.



Reduce time for standard DB actions :



Most queries in database development are simple “insert, update, delete” statements. There is no need to develop all these tedious statements. Hibernate helps you save time.Loading classes from the database looks like

Query query = session.createQuery("select st from Student as st");
for (Iterator iter = query.iterate(); iter.hasNext();) {
students.add( (Bug) iter.next() );
}
return students;

saving a class “students” to the database looks like

session.update(students);

Advanced features difficult to develop yourself :


Caching solutions, transactions and other features Hibernate provides are not so easy to implement. It is actually non sense to develop something which already exist. Using Hibernate everything is there. You just have to use it.


Hibernate Advantages:

  • Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.
  • Provides simple APIs for storing and retrieving Java objects directly to and from the database.
  • If there is change in Database or in any table then the only need to change XML file properties.
  • Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
  • Hibernate does not require an application server to operate.
  • Manipulates Complex associations of objects of your database.
  • Minimize database access with smart fetching strategies.
  • Provides Simple querying of data.


Hibernate Application Architecture in Detail :




Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.


java.lang.Object
  extended bynet.sf.hibernate.cfg.Configuration
The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. 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.
  • 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 intern configures 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 and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

here we go for Hibernate SessionFactory Example


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. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.


Transaction Object:

java.lang.Object
  extended byorg.springframework.orm.hibernate.HibernateTransactionObject

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.


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.

Here we go for Hibernate Query Example



Criteria Object:

Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.



Core interfaces of hibernate framework:


There are many benefits from these. Out of which the following are the most important one.
  1. Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
  2. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
  3. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
  4. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
  5. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.


Hibernate Properties:


Following is the list of important properties you would require to configure for a databases in a standalone situation.

  • hibernate.dialect 
    • This property makes Hibernate generate the appropriate SQL for the chosen database.
  • hibernate.connection.driver_class
    • The JDBC driver class. 
  • hibernate.connection.url 
    • The JDBC URL to the database instance.
  • hibernate.connection.username
    • The database username.
  • hibernate.connection.password 
    • The database password.
  • hibernate.connection.pool_size
    • Limits the number of connections waiting in the Hibernate database connection pool. 
  • hibernate.connection.autocommit 
    • Allows autocommit mode to be used for the JDBC connection.

Hibernate with MySQL Database:

MySQL is one of the most popular open-source database systems available today. Let us create hibernate.cfg.xml configuration file and place it in the root of your application's class path. You would have to make sure that you have testdb database available in your MySQL database and you have a user test available to access the database.
The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available from http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<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">
      root123
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Student.hbm.xml"/>

</session-factory>
</hibernate-configuration>


Here we go for Hibernate Simple Example