Académique Documents
Professionnel Documents
Culture Documents
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.
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);
}
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
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
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.
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.
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")
@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.
@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.
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.
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;
}
}