Module-5
Hibernate & Springs
Hibernate-Introduction
• Hibernate is a high-performance Object/Relational persistence
and query service, which is licensed under the open source
GNU Lesser General Public License (LGPL) and is free to
download.
• Hibernate not only takes care of the mapping from Java
classes to database tables (and from Java data types to SQL
data types), but also provides data query and retrieval
facilities.
What is JDBC?
• JDBC stands for Java Database Connectivity.
• It provides a set of Java API for accessing the relational
databases from Java program.
• These Java APIs enables Java programs to execute SQL
statements and interact with any SQL compliant database.
• JDBC provides a flexible architecture to write a database
independent application that can run on different platforms
and interact with different DBMS without any modification.
Pros and Cons of JDBC
Pros of JDBC Cons of JDBC
Complex if it is used in large projects
Clean and simple SQL processing Large programming overhead
Good performance with large data No encapsulation
Very good for small applications Hard to implement MVC(Model, View,
Simple syntax so easy to learn Controller) concept
Query is DBMS specific
Why Object Relational Mapping (ORM)?
• When we work with an object-oriented system, there is a
mismatch between the object model and the relational
database.
• RDBMS 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 the above objects are 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 a few pages or our
application?
• Second, loading and storing objects in a relational
database exposes us to the following 5 mismatch
problems
• The Object-Relational Mapping (ORM) is the solution to
handle all the above impedance mismatches.
• What is ORM?
• ORM stands for Object-Relational Mapping (ORM) is a
programming technique for converting data between
relational databases and object-oriented programming
languages such as Java, C#, etc.
• An ORM system has the following advantages over plain
JDBC
Java ORM Frameworks
• There are several persistent frameworks and ORM options in
Java.
• A persistent framework is an ORM service that stores and
retrieves objects into a relational database.
• Enterprise JavaBeans Entity Beans
• Java Data Objects
• Castor
• TopLink
• Spring DAO
• Hibernate and many more
• Hibernate is an ORM solution for JAVA.
• It is 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 relieves the developer from 95% of
common data persistence related programming tasks.
• Hibernate sits between traditional Java objects and database server to
handle all the works in persisting those objects based on the
appropriate O/R mechanisms and patterns.
Hibernate Advantages
1. Hibernate takes care of mapping Java classes to database
tables using XML files and without writing any line of code.
2. Provides simple APIs for storing and retrieving Java objects
directly to and from the database.
3. If there is change in the database or in any table, then you
need to change the XML file properties only.
4. Abstracts away the unfamiliar SQL types and provides a way
to work around familiar Java Objects.
5. Hibernate does not require an application server to operate.
6. Manipulates Complex associations of objects of your database.
7. Minimizes database access with smart fetching strategies.
8. Provides simple querying of data.
Supported Databases
• Hibernate supports almost all the major RDBMS.
• Following is a list of few of the database engines supported by
Hibernate
• HSQL Database Engine
• DB2/NT
• MySQL
• PostgreSQL
• FrontBase
• Oracle
• Microsoft SQL Server Database
• Sybase SQL Server
• Informix Dynamic Server
Supported Technologies
• Hibernate supports a variety of other technologies,
including
• XDoclet Spring
• J2EE
• Eclipse plug-ins
• Maven
Hibernate - Architecture
• Hibernate has a layered architecture which helps the user
to operate without having to know the underlying APIs.
• Hibernate makes use of the database and configuration
data to provide persistence services (and persistent
objects) to the application.
• Following is a very high level view of the Hibernate
Application Architecture.
• Following is a detailed view of the Hibernate Application
Architecture with its 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.
Configuration Object
• The Configuration object is the first Hibernate object you create in
any Hibernate application.
• It is usually created only once during application initialization.
• It represents a configuration or properties file required by the
Hibernate.
The Configuration object provides 2 keys components −
1. Database Connection − This is handled through one or more
configuration files supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.
2. Class Mapping Setup − This component creates the connection
between the Java classes and database tables.
SessionFactory Object
• SessionFactory object 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 a heavyweight object; it is usually
created during application start up and kept for later use.
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
• 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.
Criteria Object
• Criteria objects are used to create and execute object-
oriented criteria queries to retrieve objects.
Hibernate - Configuration
• Hibernate requires to know in advance where to find the
mapping information that defines how your Java classes relate
to the database tables.
• Hibernate also requires a set of configuration settings related
to database and other related parameters.
• All such information is usually supplied as a standard Java
properties file called hibernate.properties, or as an XML file
named hibernate.cfg.xml.
Hibernate Properties
• If you are using a database along with an application server
and JNDI, then you would have to configure the following
properties
Hibernate - Sessions
• 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.
• The main function of the Session is to offer, create, read, and delete
operations for instances of mapped entity classes.
Instances may exist in one of the following 3 states at a given
point in time −
1. transient − A new instance of a persistent class, which is
not associated with a Session and has no representation in
the database and no identifier value is considered transient
by Hibernate.
2. persistent − You can make a transient instance persistent
by associating it with a Session. A persistent instance has a
representation in the database, an identifier value and is
associated with a Session.
3. detached − Once we close the Hibernate Session, the
persistent instance will become a detached instance.
• A Session instance is serializable if its persistent classes
are serializable. A typical transaction should use the
following idiom
• If the Session throws an exception, the transaction must
be rolled back and the session must be discarded.
Session Interface Methods
• There are number of methods provided by
the Session interface
Hibernate With Annotation
• 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.
Environment Setup for Hibernate Annotation
1. Make sure that you are using JDK 5.0 otherwise you need to upgrade your
JDK to JDK 5.0 to take advantage of the native support for annotations.
2. You will need to install the Hibernate 3.x annotations distribution package,
available from the sourceforge: (Download Hibernate Annotation) and
copy hibernate-annotations.jar, lib/hibernate-comons-
annotations.jar and lib/ejb3-persistence.jar from the Hibernate
Annotations distribution to your CLASSPATH.
Annotated Class Example
• Consider we are going to use the following EMPLOYEE
table to store our objects
• 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; }
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.
@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 4 attributes, allowing you
to override the name of the table, its catalogue, and its
schema, and enforce unique constraints on columns in the
table.
@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
@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.
• nullable 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.
Create Application Class
• Finally, we will create our application class with the
main() method to run the application.
• We will use this application to save few Employee's
records and then we will apply CRUD operations on
those records.
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee { private static SessionFactory
factory;
public static void main(String[] args)
{ try
{ factory = new AnnotationConfiguration(). configure().
//addPackage("com.xyz") //add package if used.
addAnnotatedClass(Employee.class). buildSessionFactory(); }
catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex); }
ManageEmployee ME = new ManageEmployee(); /* Add few employee records in
database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 10000); /* List down all
the employees */
ME.listEmployees(); /* Update employee's records */
ME.updateEmployee(empID1, 5000);
/* Delete an employee from the database */ ME.deleteEmployee(empID2);
/* List down new list of the employees */
ME.listEmployees(); }
/* Method to CREATE an employee in the database */
public Integer addEmployee(String fname, String lname, int salary)
{ Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try { tx = session.beginTransaction();
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
employeeID = (Integer) session.save(employee);
tx.commit(); }
catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); }
finally { session.close(); } return employeeID; }
/* Method to READ all the employees */
public void listEmployees( ){ Session session =
factory.openSession(); Transaction tx = null;
try { tx = session.beginTransaction();
List employees = session.createQuery("FROM
Employee").list();
for (Iterator iterator = employees.iterator();
iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " +
employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary()); }
tx.commit(); }
}
catch (HibernateException e) {
if (tx!=null)
tx.rollback();
e.printStackTrace(); }
finally {
session.close(); } }
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try { tx = session.beginTransaction();
Employee employee = (Employee)
session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit(); }
catch (HibernateException e) {
if (tx!=null) tx.rollback(); e.printStackTrace(); }
finally { session.close(); } }
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID){ Session session =
factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Employee employee = (Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit(); }
catch (HibernateException e) {
if (tx!=null)
tx.rollback();
e.printStackTrace(); }
finally {
session.close(); } }
Database Configuration
• Create hibernate.cfg.xml configuration file to define
database related parameters.
<?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 students 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"> cohondob
</property>
</session-factory> </hibernate-configuration>
Compilation and Execution
• Steps to compile and run the application.
• Set PATH and CLASSPATH appropriately before proceeding for the
compilation and execution.
• Delete Employee.hbm.xml mapping file from the path.
• Create Employee.java source file as shown above and compile it.
• Create ManageEmployee.java source file as shown above and compile
it.
• Execute the ManageEmployee binary to run the program.
Hibernate Validator
• Hibernate Validators offer field-level validation for every attribute
of a bean class, which means you can easily validate a field
content against null/not null, empty/not empty, with min/max
value to a specific value, valid email, and valid credit card, etc.,
• All Hibernate Validators are available for both server and client
application programming.
• These Hibernate validators help in transparent integration
because of their standard validation rules.