Happy Diwali
happy diwali

Saturday, 7 June 2014

Hibernate Basic simple Program

Hibernate
Hibernate is a backend framework, free to use, open source developed purely in java. Its working based on ORM – Object Relational Mapping.
Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool.
An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the data


Advantages of using Hibernate
In place of JDBC we can use hibernate. If we use JDBC to interact with the database, we need to develop several statements (steps) to send a SQL Query to the database like registering a driver, establishing a database connection object, getting a statement object, comparing SQL Query, sending SQL Query to the database, getting the results from the database, processing those results and finally closing all the JDBC related resources.
While using hibernate no need for any of these steps, straightaway pass java object to the hibernate framework. Hibernate framework will take care of interacting with JDBC API, like registering a driver, establishing a connection object, composing sql query based on data of java object etc.
Java program will be independent of database code, so we can change the database like oracle, MySql….. we just have to change one configuration file to make the changes.
JDBC gets the result immediately after getting the query, it doesn’t check if the user is using that result or not. In Hibernate it waits till the user to use that row, then sends the query and gets the result.
Hibernate Architecture
There are 4 layers in hibernate architecture java application layer, hibernate framework layer, backhand api layer and database layer.Let's see the diagram of hibernate architecture:

This is the high level architecture of Hibernate with mapping file and configuration file.

Elements of Hibernate Architecture

For creating the first hibernate application, we must know the elements of Hibernate architecture. They are as follows:

SessionFactory

The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.

Session

The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction interface provides methods for transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.
Two types of loading data from database in hibernate
1.       Eager Loading
Framework loads data immediately after executing query to get the data,.

2.       Lazy Loading
It does not load data immediately when asked to load, it will be looking for the statement which is using that data, just before executing that statement framework will be loading that data.
Hibernate supports both type of loading and the default one is lazy loading.

In case of JDBC no cache mechanism, no temporary memory to store data. Every time connects to the db and gets the data (a network flow from java program to database).
Hibernate supports two levels of cache mechanism: First Level cache and Second Level.
First level cache is the default. Second level we have to provide explicitly.

JDBC is not providing any auto increment values to the unique column of the table. (In general for every table there should be a auto increment column.) JDBC programmer has to manually increment the unique column(used to identify the row and count total number of rows).
Hibernate supports auto generated random unique number.

JDBC supports only updatable operations without transactions. No transaction boundaries required while updating, editing or deleting a row. No updatable operations without a transaction in case of Hibernate.
E.g.: In a table if column of a particular row are changed at different statement, Framework updates only at the time of commit statement. It will update all changes at once. JDBC modifies immediately, even if updating same row and same column again and again.

Hibernate supports Polymorphic mappings and Association mappings, through this we can easily achieve relationships among the tables.

Mainly three types of relations among the tables
1.       One-to-one: One row of one table mapping with a particular row of another table.
2.       One-to-many: One row of 1st table mapping with multiple rows of 2nd table.
3.       Many-to-many: One row of 1st table mapping with Multiple rows of 2nd table. One row of 2nd table mapping with multiple rows of 1st table.
Hibernate supports Annotation mappings
EJB3 and Hibernate developers provide several annotations used for providing a mapping (easy way of providing a mapping). No need for additional classes for mapping. Annotation itself contains them, it gives ultimate performance.


How to use Hibernate Framework
1.       EclipseàNewàProject àJava Project. Project Name: app1
Updating the Build Path:
Right click on app1àPropertiesàJava Build PathàLibrariesàAdd External JARsàBrowse to
Location of the Hibernate un zipped  folder And  add all jar files inside HIBERNATE\hibernate-distribution-4..1.1\lib\required by selecting all.
Again Add the Oracle jdbc driver jar file
D:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar
Copy the hibernate.cfg.xml and log4j.properties file from inside Hibernate unzipped bundle go to D:\Java\hibernate\project\tutorials\web\src\main\resources\
Right click on src and paste. The hibernate.cfg.xml is used to identify the type of database, driver class name, url etc.
The log4j.properties file is not mandatory but is advisable.
While developing for the first time since we won’t be knowing the tags of the hibernate.cfg.xml file, we are using the model file.
Inside hibernate.cfg.xml file make the following changes marked in bold:
<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<propertyname="connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<propertyname="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<propertyname="connection.username">system</property>
<propertyname="connection.password">password</property>

<!-- JDBC connection pool (use the built-in) -->
<propertyname="connection.pool_size">2</property>

<!-- SQL dialect -->
<propertyname="dialect">org.hibernate.dialect.OracleDialect</property>


<!-- Enable Hibernate's current session context -->
<propertyname="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

<!-- Disable the second-level cache  -->
<propertyname="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<propertyname="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<propertyname="hbm2ddl.auto">create</property>

<mappingresource="com/lara/Person.hbm.xml"/>
</session-factory>

</hibernate-configuration>

The SQL dialect specifies the type of database we are using to the Framework.
Right Click on srcàNewàClass
Person.java (This type of class is called as POJO (Plain Old Java object) class
package com.lara;

publicclass Person {
      private String id;
      private String firstname;
      private String lastname;
      privateintage;
      public String getId() {
            returnid;
      }
      publicvoid setId(String id) {
            this.id = id;
      }
      public String getFirstname() {
            returnfirstname;
      }
      publicvoid setFirstname(String firstname) {
            this.firstname = firstname;
      }
      public String getLastname() {
            returnlastname;
      }
      publicvoid setLastname(String lastname) {
            this.lastname = lastname;
      }
      publicint getAge() {
            returnage;
      }
      publicvoid setAge(int age) {
            this.age = age;
      }          
}
This type of class called useBean in JSP,  formBean in Struts and POJO in hibernate.
Provide one mapping xml file (copy the model file from DVD’s unzipped hibernate folder
Hibernate\project\tutorials\web\src\main\resources\org\hibernate\tutorial\domain\Person.hbm.xml and paste it by right clicking on lara folder in eclipse).

Make the following changes in Person.hbm.xml
<hibernate-mappingpackage="com.lara">

<classname="Person"table="PERSON">
<idname="id"column="PERSON_ID">
<generatorclass="native"/>
</id>
<propertyname="age"/>
<propertyname="firstname"/>
<propertyname="lastname"column="last_name"/>

</class>
</hibernate-mapping>

Manager.java
package com.lara;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

publicclass Manager {
      publicstaticvoid main(String[] args) {
            Person p1 = new Person();
            p1.setFirstname("abc");
            p1.setLastname("xyz");
            p1.setAge(25);
           
            Configuration c1 = new Configuration();
            c1.configure();
           
            SessionFactory sf = c1.buildSessionFactory();
            Session session = sf.openSession();
      }
}

No comments:

Post a Comment

happy diwali
happy diwali