Hibernate: Advantage of Hibernate Over JDBC
Hibernate: Advantage of Hibernate Over JDBC
Hibernate: Advantage of Hibernate Over JDBC
Advantage are
1) Hibernate is data base independent, same code will work for all data bases like
ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.
3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then
hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level.
So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache
5) Hibernate supports Query cache and It will provide the statistics about your query and database
status.
JDBC Not provides any statistics.
6) Development fast in case of Hibernate because you don't need to write queries.
7) No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool.
8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
9) You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don't have such support.
10 ) Hibernate Supports automatic versioning of rows but JDBC No
testApp
|
----src // Java Source Code folder
|
-------------beans //Source Code folder
|
----------------Offer.java //Source Code
-------------servlet //Source Code folder
|
----------------DBStartUpServlet.java //Source Code
-------------dao //Source Code folder
|
----------------HibernateUtil.java //Source Code
----config // config folder where all the configuration files present
|
-------------hibernate.cfg.xml //Hibernate Config file
-------------Offer.hbm.xml// hibernate mapping with Offer TABLE
-------------log4j.properties// log4j setting
----WEB-INF //within folder
|
---------web.xml //file
---------classes //folder
---------lib //within folder
|
-------------hibernate3.jar //jar file
-------------antlr-2.7.6rc1.jar //jar file
-------------asm.jar //jar file
-------------asm-attrs.jar //jar file
-------------c3p0-0.9.0.jar //jar file for connection pool
-------------classes12.jar //if you use ORACLE DATABASE jar file
-------------mysql-connector-java-5.0.4-bin.jar //if you use MySQL DATABASE jar file
-------------commons-logging.jar //jar file
-------------commons-validator.jar //jar file
-------------dom4j-1.6.1.jar //jar file
-------------jta.jar //jar file
-------------log4j-1.2.11.jar //jar file
-------------nls_charset12.jar //jar file
This servlet is only for load configuration files related to Hibernate and create Session Factory
on start up .
Create Session Factory is very Expensive
Create Session Factory is very Expensive so we added one servlet to create on server startup
Initialize Connection pool on startup
Initialize Connection pool on startup using c3p0.
Initialize log4j configuration
Initialize log4j configuration on startup.
package servlet;
public class DBStartUpServlet extends HttpServlet {
/** Initialising the Logger */
protected static final Logger
logger=Logger.getLogger(DBStartUpServlet.class);
public void init(ServletConfig config) throws
ServletException {
System.out.println("\n**** Initializing Hibernate Init
Servlet ********** \n");
super.init(config);
}
}
s = getSessionFactory().openSession();
threadSession.set(s);
// logger.debug("session 1 $"+s);
}
return s;
}
package beans;
public class Offer {
private long offerId;
private String offerName;
/**
* @return Returns the offerId.
*/ public long getOfferId() {
return offerId;
}
/**
* @param offerId The offerId to set.
*/
private void setOfferId(long offerId) {
this.offerId = offerId;
}
/** * @return Returns the offerName.
*/
public String getOfferName() {
return offerName;
}
/**
* @param offerName The offerName to set.
*/
public void setOfferName(String offerName) {
this.offerName = offerName;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Offer" table="OFFER">
<id name="offerId" column="offer_id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="offerName" column="offer_name"/>
</class>
</hibernate-mapping>
This section describe a simple program to insert record into database and fetch the records
Follow the setps
// for MySQL
create table EMPLOYEE (
id bigint(20) ,
name varchar
);
// FOR ORACLE
create table EMPLOYEE (
id number;
name varchar
);
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Emp" table="EMPLOYEE">
<id name="id" column="id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="name" column="name"/>
</class>
</hibernate-mapping>
Hibernate provided connection pooling usning c3p0 and transaction management . Hibernate
uses the hibernate.cfg.xml to create the connection pool and setup required environment
Hibernate Session is the main runtime interface for Hibernate which is used for DataBase
operataion. Session has the method like save () , update () , creteQuery() for Data Base operation.
You can get session using SessionFactory.openSession() method. SessionFactory allows
application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml
file. Then the save () method on session object is used to save the contact information to the
database.
package beans;
public class Offer {
private long offerId;
private String offerName;
/**
* @return Returns the offerId.
*/ public long getOfferId() {
return offerId;
}
/**
* @param offerId The offerId to set.
*/
private void setOfferId(long offerId) {
this.offerId = offerId;
}
/** * @return Returns the offerName.
*/
public String getOfferName() {
return offerName;
}
/**
* @param offerName The offerName to set.
*/
public void setOfferName(String offerName) {
this.offerName = offerName;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Offer" table="OFFER">
<id name="offerId" column="offer_id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="offerName" column="offer_name"/>
</class>
</hibernate-mapping>
There are two table WRITER and STORY. One writer can write multiple stories. So the relation
is one-to-many uni-directional.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Writer" table="WRITER">
<id name="id" column="ID" type="int" unsaved-value="0">
<generator class="increment"/>
</id>
<list name="stories" cascade="all">
<key column="parent_id"/>
<one-to-many class="Story"/>
</list>
<property name="name" column="NAME" type="string"/>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Story" table="story">
<id name="id" column="ID" type="int" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="info" column="INFO" type="string"/>
</class>
</hibernate-mapping>
Save Example ..
Writer wr = new Writer();
wr.setName("Das");
ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));
wr.setStories(list);
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(wr);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
throw e;
}
} finally {
session.close();
}
There are two table WRITER and STORY. One writer can write multiple stories. So the relation
is one-to-many . This tutorial describe the bi-directional relation. From WRITER object you can
get list of Stories and from story object you can get writer object.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Writer" table="WRITER">
<id name="id" column="ID" type="int" unsaved-value="0">
<generator class="increment"/>
</id>
<list name="stories" cascade="all">
<key column="parent_id"/>
<one-to-many class="Story"/>
</list>
<property name="name" column="NAME" type="string"/>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Story" table="story">
<id name="id" column="ID" type="int" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="info" column="INFO" type="string"/>
<many-to-one name="writer" column="ID" lazy="false"/>
</class>
</hibernate-mapping>
There are two table EVENTS and SPEAKERS . One Event can have multiple speakers. And One
Speaker can speak in multiple Event. So this is many to many relation. To maintain this relation
we have to introduce third TABLE name EVENT_SPEAKERS .
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Event" table="events">
<id name="id" column="event_id" type="long">
<generator class="increment"/>
</id>
<property name="name" column="event_name" type="string"
length="100"/>
<set name="speakers" table="event_speakers" cascade="all">
<key column="event_id"/>
<many-to-many class="Speaker"/>
</set>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Speaker" table="speakers">
<id name="id" column="speaker_id" type="long">
<generator class="increment"/>
</id>
<property name="name" column=" speaker_name" type="string"
length="100"/>
<set name="events" table="event_speakers" cascade="all">
<key column="speaker_id"/>
<many-to-many class="Event"/>
</set>
</class>
</hibernate-mapping>
HQL: The Hibernate Query Language The Hibernate Query Language is executed using
session.createQuery(). This tutorial includes from clause,Associations and joins, Aggregate
functions,The order by clause,The group by clause,Subqueries.
Aggregate functions
Subqueries
from Employee as e
where e.name = some (
select name.nickName from Name as name
)
Associations
Example queries
The class org.hibernate.criterion.Example allows you to construct a query criterion from a given
instance.
Criteria Queries : Equal (eq), Not Equal(ne), Less than (lt), Less than or equal(le), greater
than (gt),greater than or equal(ge) and Ordering the results The interface
org.hibernate.Criteria represents a query against a particular persistent class. The Session is a
factory for Criteria instances. In this section it show how to create TABLE and POJO Java class
and Mapping with the Query.
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table
(Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database
column.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<id name="id" column="id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="name" column="name"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
Equal (eq)
NotEqual (ne)
Less than or equal(le) : Is used to check less than or equal in the query.
Greater than or equal (gt) : Is used to check greater than or equal in the query.
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table
(Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database
column.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<id name="id" column="id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="name" column="name"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
And Condtion
This method returns the conjunctions of two expressions. Both conditions are 'true' then it
excutes the query otherwise not.
OR Condtion
This method returns the disjuction of two expressions. Any given condition is 'true' then it
executes the query. In this tutorial, "or" is used
The optional <generator> child element names a Java class used to generate unique identifiers
for instances of the persistent class
increment generates identifiers of type long, short or int that are unique only when no other
process is inserting data into the same table. Do not use in a cluster. Follow the setps :
// for MySQL
create table EMPLOYEE (
id bigint(20) ,
name varchar
);
// FOR ORACLE
create table EMPLOYEE (
id number;
name varchar
);
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table
(Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database
column.
Step 3. Emp.hbm.xml - This mapps EMPLOYEE TABLE and Emp.java : increment for
the generator class
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Emp" table="EMPLOYEE">
<id name="id" column="id" type="long">
<generator class="increment"/> // This generates the primary key
</id>
<property name="name" column="name"/>
</class>
</hibernate-mapping>
Hibernate provided connection pooling usning c3p0 and transaction management . Hibernate
uses the hibernate.cfg.xml to create the connection pool and setup required environment
Hibernate Session is the main runtime interface for Hibernate which is used for DataBase
operataion. Session has the method like save () , update () , creteQuery() for Data Base operation.
You can get session using SessionFactory.openSession() method. SessionFactory allows
application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml
file. Then the save () method on session object is used to save the contact information to the
database.
Step 1. Declare a variable "versionId" in your bean Class with setter and getter method.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Writer" table="WRITER" optimistic-lock="version">
<id name="id" column="ID" type="int" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name" column="NAME" type="string"/>
<version name="versionId" type="long" column="version" />
</class>
</hibernate-mapping>
When you are updating the table just check the version with you and the current version in the
table.
You can handle StaleObjectStateException() and do what ever you want.
You can display error message.
Hibernate autumatically create/update the version number when you update/insert any row in the
table.
In the code
session = sf.openSession();
long oldVersion = writer.getVersionId();
// User Think time ::::::::::::::: May be 1 minute then get the current
version using load() method below.
session.load( writer, writer.getId() ); // current version in the table
if ( oldVersion!=writer.getVersionId() ) throw new
StaleObjectStateException();
//check the version with you and the current version in the table
writer.setName("Das");
session.flush();
session.connection().commit();
session.close();