Vous êtes sur la page 1sur 15

Table of Contents

1. INTRODUCTION TO JDBC ................................................................................................................ 2


2. JDBC ARCHITECTURE ...................................................................................................................... 2
3. INTERACTION WITH RDBMS .......................................................................................................... 2
3. Why Object Relational Mapping (ORM)? ...................................................................................... 3
4. INTRODUCTION TO HIBERNATE.................................................................................................... 4
5. HIBERNATE ARCHITECTURE .......................................................................................................... 5
5.1. CONFIGURATION OBJECT .............................................................................................................. 6
5.2. SESSIONFACTORY OBJECT ............................................................................................................. 7
5.3. SESSION OBJECT ........................................................................................................................... 7
5.4. TRANSACTION OBJECT .................................................................................................................. 7
5.5. QUERY OBJECT .............................................................................................................................. 7
5.6. CRITERIA OBJECT........................................................................................................................... 7
6. HIBERNATE COMMUNICATION WITH RDBMS ............................................................................. 8
7. HIBERNATE ANNOTATIONS....................................................................................................... 10
8. JDBC Vs Hibernate ......................................................................................................................... 12
8.1 WHY IS HIBERNATE BETTER THAN JDBC ....................................................................................... 12
8.2 DISADVANTAGES OF HIBERNATE.................................................................................................. 13

1. INTRODUCTION TO JDBC
JDBC stands for Java Database Connectivity allows developers to connect, query and update a database
using the Structured Query Language. JDBC API standard provides Java developers to interact with
different RDBMS and access table data through Java application without learning RDBMS details and
using Database Specific JDBC Drivers.

2. JDBC ARCHITECTURE
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access
database:
Open connection to database,
use JDBC driver to send SQL queries to database,
process the results that are returned, and
close the connection.
JDBC uses two architectures to communicate with database:
1) The driver connects to database and executes SQL statements. Results are sent back from driver
to driver manager and finally to the application.
2) The JDBC driver communicates with ODBC driver. ODBC driver executes SQL query and then
results are sent back to JDBC driver to driver manager and then to application.

3. INTERACTION WITH RDBMS


General steps:
1) Load the RDBMS specific JDBC driver because this driver actually communicates with the
database.
2) Open the connection to database which is then used to send SQL statements and get results back.
3) Create JDBC Statement object. This object contains SQL query.

4) Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a
result of SQL query.
5) Process the result set.
6) Close the connection.
Example: Retrieve list of employees from Employee table using JDBC.
String url = jdbc:odbc: + dbName;
List<EmployeeBean> employeeList = new ArrayList<EmployeeBean>();
/* load the jdbc-odbc driver */
class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
/* Open a connection to database */
Connection con = DriverManager.getConnection(url);
/* create Statement object */
Statement stmt = con.createStatement();
/* execute statement */
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee");
while ( rs.next() )
{
EmployeeBean eb = new Employeebean();
eb.setName(rs.getString("name"));
eb.setSalary(rs.getFloat("salary"));
employeeList.add(eb);
}

3. Why Object Relational Mapping (ORM)?


When we work with an object-oriented systems, there's a mismatch between the object model
and the relational database. RDBMSs represent data in a tabular format whereas object-oriented
languages, such as Java or C# represent it as an interconnected graph of objects. Consider the
following Java Class with proper constructors and associated public function:
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {

return last_name;
}
public int getSalary() {
return salary;
}
}

Consider above objects need to be stored and retrieved into the following RDBMS table:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary
INT default NULL,
PRIMARY KEY (id)
);

First problem, what if we need to modify the design of our database after having developed few
pages or our application? Second, Loading and storing objects in a relational database exposes us
to the following five mismatch problems.
Mismatch

Description

Granularity

Sometimes you will have an object model which has more classes than the number
of corresponding tables in the database.

Inheritance

RDBMSs do not define anything similar to Inheritance which is a natural paradigm


in object-oriented programming languages.

Identity

A RDBMS defines exactly one notion of 'sameness': the primary key. Java, however,
defines both object identity (a==b) and object equality (a.equals(b)).

Associations

Object-oriented languages represent associations using object references where as


am RDBMS represents an association as a foreign key column.

Navigation

The ways you access objects in Java and in a RDBMS are fundamentally different.

The Object-Relational Mapping (ORM) is the solution to handle all the above impedance
mismatches.

4. INTRODUCTION TO HIBERNATE
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance
object/relational persistence and query service. It allows us to develop persistent classes following
object-oriented idiom including association, inheritance and polymorphism.

5. HIBERNATE ARCHITECTURE
Hibernate:
1) Itself opens connection to database,
2) Converts HQL (Hibernate Query Language) statements to database specific statement,
3) Receives result set,
4) Then performs mapping of these databases specific data to Java objects which are directly used
by Java application.
Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is
performed on the basis of the properties defined in hbm XML file defined for particular Java object.

Following is a detailed view of the Hibernate Application Architecture with few important core
classes.

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.
Following section gives brief description of each of the class objects involved in Hibernate
Application Architecture.

5.1. CONFIGURATION OBJECT


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..

5.2. SESSIONFACTORY OBJECT


Configuration object is used to create a SessionFactory object which in turn 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.

5.3. 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.

5.4. TRANSACTION OBJECT


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.

5.5. 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.

5.6. CRITERIA OBJECT


Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

6. HIBERNATE COMMUNICATION WITH RDBMS


General steps:
1. Load the Hibernate configuration file and create configuration object. It will automatically load all
hbm mapping files.
2. Create session factory from configuration object
3. Get one session from this session factory.
4. Create HQL query.
5. Execute query to get list containing Java objects.
Example: Retrieve list of employees from Employee table using Hibernate.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
The XML Hibernate configuration file
<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="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

SessionFactory

The SessionFactory is the concept that is a single data store and thread safe. Because of this feature,
many threads can access this concurrently and the sessions are requested, and also the cache that is
immutable of compiled mappings for a specific database. A SessionFactory will be built only at the time
of its startup. In order to access it in the application code, it should be wrapped in singleton. This
wrapping makes the easy accessibility to it in an application code.

SessionFactory is an interface and extends Referenceable, Serializable


Creates Sessions. Usually an application has a single SessionFactory. Threads servicing client
requests obtain Sessions from the factory.
Implementors must be threadsafe.
SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties
supplied at configuration time. These properties are defined on Environment.
SessionFactory is an interface, which is available in org.hibernate package.
Session factory is long live multithreaded object.
Usually one session factory should be created for one database.
When you have multiple databases in your application you should create multiple
SessionFactory object.
Assume the scenario that you are using one database called mysql in your application then
following is the way to create the SessionFactory object.

/* Load the hibernate configuration file */


Configuration cfg = new Configuration();
cfg.configure(CONFIG_FILE_LOCATION);
example
Configuration cfg=cfg.configure(mysql.cfg.xml);
/* Create the session factory */
SessionFactory sessionFactory = cfg.buildSessionFactory();
/* Retrieve the session */
Session session = sessionFactory.openSession();
/* create query */
Query query = session.createQuery("from EmployeeBean);
/* execute query and get result in form of Java objects */
List<EmployeeBean> finalList = query.list();

EmployeeBean.hbm.xml File
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.mf.bean.EmployeeBean"
table="t_employee">
<id name="id" type="string" unsaved-value="null">
<column name="id" sql-type="varchar(32)" not-null="true"/>
<generator class="uuid"/>
</id>

<property name="name">
<column name="name" />
</property>
<property name="salary">
<column name="salary" />
</property>
</class>
</hibernate-mapping>

7. HIBERNATE ANNOTATIONS
So far you have seen how Hibernate uses XML mapping file for the transformation of data from POJO to
database tables and vice versa. Hibernate annotations are the newest way to define mappings without
the use of XML file. You can use annotations in addition to or as a replacement of XML mapping
metadata.
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table
mapping. All the metadata is clubbed into the POJO java file along with the code; this helps the user to
understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must use
annotations to represent the mapping information, but still if you want greater flexibility, then you
should go with XML-based mappings.
Annotated Class Example
As I mentioned above while working with Hibernate Annotation, all the metadata is clubbed into the
POJO java file along with the code, this helps the user to understand the table structure and POJO
simultaneously during the development.
Consider we are going to use the following EMPLOYEE table to store our objects:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Following is the mapping of Employee class with annotations to map objects with the defined
EMPLOYEE table:
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")

private String firstName;


@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name; Hibernate
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
Hibernate detects that the @Id annotation is on a field and assumes that it should access properties of
an object directly through fields at runtime. If you placed the @Id annotation on the getId() method, you
would enable access to properties through getter and setter methods by default. Hence, all other
annotations are also placed on either fields or getter methods, following the selected strategy.
Following section will explain the annotations used in the above class.

@Entity Annotation
The EJB 3 standard annotations are contained in the javax.persistence package, so we import this
package as the first step. Second, we used the @Entity annotation to the Employee class, which marks
this class as an entity bean, so it must have a no-argument constructor that is visible with at least
protected scope.

@Table Annotation
The @Table annotation allows you to specify the details of the table that will be used to persist the
entity in the database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its
catalogue, and its schema, and enforce unique constraints on columns in the table. For now, we are
using just table name, which is EMPLOYEE.

@Id and @GeneratedValue Annotations


Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The
primary key can be a single field or a combination of multiple fields depending on your table structure.
By default, the @Id annotation will automatically determine the most appropriate primary key
generation strategy to be used but you can override this by applying the @GeneratedValue annotation,
which takes two parameters strategy and generator that I'm not going to discuss here, so let us use only
the default key generation strategy. Letting Hibernate determine which generator type to use makes
your code portable between different databases.

@Column Annotation
The @Column annotation is used to specify the details of the column to which a field or property will be
mapped. You can use column annotation with the following most commonly used attributes:
Name attribute permits the name of the column to be explicitly specified.
Length attribute permits the size of the column used to map a value particularly for a String
value.
null able attribute permits the column to be marked NOT NULL when the schema is generated.
Unique attribute permits the column to be marked as containing only unique values.

8. JDBC Vs Hibernate
8.1 WHY IS HIBERNATE BETTER THAN JDBC
1) Relational Persistence for JAVA
Working with both Object-Oriented software and Relational Database is complicated task with
JDBC because there is mismatch between how data is represented in objects versus relational
database. So with JDBC, developer has to write code to map an object model's data representation
to a relational data model and its corresponding database schema. Hibernate is flexible and
powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this
mapping using XML files so developer does not need to write code for this.
2) Transparent Persistence
The automatic mapping of Java objects with database tables and vice versa is called Transparent
Persistence. Hibernate provides transparent persistence and developer does not need to write
code explicitly to map database tables tuples to application objects during interaction with RDBMS.
With JDBC this conversion is to be taken care of by the developer manually with lines of code.
3) Support for Query Language
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient
way to access database, i.e to select effective query from a number of queries to perform same
task. Hibernate provides a powerful query language Hibernate Query Language (independent from
type of database) that is expressed in a familiar SQL like syntax and includes full support for
polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective
way to perform a database manipulation task for an application.
4) Database Dependent Code
Application using JDBC to handle persistent data (database tables) having database specific code in
large amount. The code written to map table data to application objects and vice versa is actually
to map table fields to object properties. As table changed or database changed then its essential to
change object structure as well as to change code written to map table-to-object/object-to-table.
Hibernate provides this mapping itself. The actual mapping between tables and application objects
is done in XML files. If there is change in Database or in any table then the only need to change XML
file properties.

5) Maintenance Cost
With JDBC, it is developers responsibility to handle JDBC result set and convert it to Java objects
through code to use this persistent data in application. So with JDBC, mapping between Java
objects and database tables is done manually. Hibernate reduces lines of code by maintaining
object-table mapping itself and returns result to application in form of Java objects. It relieves
programmer from manual handling of persistent data, hence reducing the development time and
maintenance cost.
6) Optimize Performance
Caching is retention of data, usually in application to reduce disk access. Hibernate, with
Transparent Persistence, cache is set to application work space. Relational tuples are moved to this
cache as a result of query. It improves performance if client application reads same data many
times for same write. Automatic Transparent Persistence allows the developer to concentrate more
on business logic rather than this application code. With JDBC, caching is maintained by handcoding.
7) Automatic Versioning and Time Stamping
By database versioning one can be assured that the changes done by one person is not being roll
backed by another one unintentionally. Hibernate enables developer to define version type field to
application, due to this defined field Hibernate updates version field of database table every time
relational tuple is updated in form of Java class object to that table. So if two users retrieve same
tuple and then modify it and one user save this modified tuple to database, version is automatically
updated for this tuple by Hibernate. When other user tries to save updated tuple to database then
it does not allow saving it because this user does not has updated data. In JDBC there is no check
that always every user has updated data. This check has to be added by the developer.
8) Open-Source, Zero-Cost Product License
Hibernate is an open source and free to use for both development and production deployments.
9) Enterprise-Class Reliability and Scalability
Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds
of users or for mission-critical applications that serve hundreds of thousands. JDBC cannot be
scaled easily.

8.2 DISADVANTAGES OF HIBERNATE


1) Steep learning curve.
2) Use of Hibernate is an overhead for the applications which are :
Simple and use one database that never change
need to put data to database tables, no further SQL queries
There are no objects which are mapped to two different tables
Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best
choice.
3) Support for Hibernate on Internet is not sufficient.
4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.
5) For complex data, mapping from Object-to-tables and vice versa reduces performance and increases
time of conversion.
6) Hibernate does not allow some type of queries which are supported by JDBC. For example It does
not allow to insert multiple objects (persistent data) to same table using single query. Developer
has to write separate query to insert each object.

JAVA SERVLET
A Java servlet is a Java program that extends the capabilities of a server. Although servlets can respond
to any types of requests, they most commonly implement applications hosted on Web servers. Such
Web servlets are the Java counterpart to other dynamic Web content technologies such as PHP and
ASP.NET.
JavaBeans
In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a
single object (the bean). They are serializable, have a zero-argument constructor, and allow access to
properties using getter and setter methods.
Persistent classes
Java classes whose objects or instances will be stored in database tables are called persistent classes in
Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old
Java Object (POJO) programming model.

There are following main rules of persistent classes, however, none of these rules are hard
requirements.

All Java classes that will be persisted need a default constructor.


All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.
All attributes that will be persisted should be declared private and have getXXX and
setXXX methods defined in the JavaBean style.
A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.

The POJO name is used to emphasize that a given object is an ordinary Java Object, not a
special object, and in particular not an Enterprise JavaBean.
A simple POJO example:
Based on the few rules mentioned above we can define a POJO class as follows:
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {

this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}

Vous aimerez peut-être aussi