Unit 6
Unit 6
❑ Overview of Hibernate
❑ Hibernate Architecture
❑ Hibernate Annotation
• JDBC and SQL are used to retrieve data from the database.
• However, writing queries using SQL to insert, retrieve, update or delete data from a database was a
time consuming process.
• This was simplified with the introduction of Hibernate framework that provides HQL.
• As compared to SQL, in HQL we do not need to write code to perform common data persistence
related programming tasks.
3
Object Relational Mapping (ORM)
• When workingwith object-oriented system, there is a mismatch betweenobject
model and relational database.
• RDBMS represent data in tabular format where as object model represent it as interconnected graph of
objects.
• It is tool that simplifies the data creation, data manipulation and data access. It is a programming technique
that maps the object to the data stored in the database.
• The ORM tool internally uses the JDBC API to interact with the database
4
Hibernate
• Hibernate framework is a lightweight ORM, which is a
technique for mapping an object model to a relational model.
• To create this mapping, a simple Plain Old Java Objects(POJO) class and XML mapping file is written.
• This XML file describes the relationship of the database with the class attributes and calls the Hibernate
APIs to load/store the persistent objects.
• Hibernate works efficiently with applications that use swings, servlets, and EJB session beans.
5
Hibernate (…)
6
Need of Hibernate
• Hibernate framework provides an extensive approach to manage
the object relational mapping and persistence management.
• The following are the reasons due to which Hibernate in Web application can be used to query or retrieve
data from the database:
1. Provides developers with persistence feature and a code generation library that helps in extending
Java classes and implementing Java interfaces at runtime environment.
o Changes made to objects are reflected in database automatically without additional coding
o Saves time
1. Provides object oriented query language HQL which is used in writing multi-criteria search and
dynamic queries 7
Need of Hibernate (…)
4. Provides Object / Relational mapping for bridging gap between object-oriented systems and relational
databases.
5. Enables the developer to build a Hibernate Web application very efficiently in MyEclipse by using
Hibernate eclipse plug-ins that provide mapping editor, interactive query prototyping and schema
reverse engineering tool.
7. Provides ID generator classes to generate surrogate keys also called as unique keys/ identifiers e.g.
Sequence, Increment etc.
8. Provides a multi level cache architecture that ensures thread safety and continuous data access.
✔SessionFactory can be easily bound to Java Naming and Directory Interface (JNDI)
✔Stateful session bean or a HttpSession servlet with load balancing to handle a session
✔Automatic binding of the Hibernate session to the global JTA transaction scope
9
Hibernate
Java Application Architecture
Transient
Layer
Hibernate Framework
Layer
Hibernate
API
Database
Layer
10
Hibernate Architecture (…)
• There are four layers in Hibernate architecture: Java application layer, Hibernate framework layer,
back-end API layer and database layer.
• Hibernate make use of existing Java APIs : JDBC, Java Transaction (JTA), JNDI.
• JDBC loads database driver and establishes a connection for accessing relational database.
11
Hibernate Architecture (…)
• Interfaces in Hibernate Framework:
o Configuration (org.hibernate.cfg.Configuration):
– It allows the application on start-up, to specify properties and mapping documents to be used when
creating a SessionFactory.
– Properties file contains database connection setup info while mapping specifies the classes to be
mapped.
o SessionFactory (org.hibernate.SessionFactory)
– It’s a thread-safe immutable object created per database & mainly used for creating Sessions.
– It caches generated SQL statements and other mapping metadata that Hibernate uses at runtime.
o Session (org.hibernate.Session)
– It’s a single-threaded object used to perform create, read, update and delete operations for instances
of mapped entity classes. 1
Hibernate Architecture (…)
• Interfaces in Hibernate Framework: (…)
– Since it’s not thread-safe, it should not be long-lived and each thread/transaction should obtain its
own instance from a SessionFactory.
– The Session object is lightweight and designed to be instantiated each time an interaction is needed
with the database.
o Transaction (org.hibernate.Transaction)
– It’s an Optional API and application may choose not to use it.
o Query (org.hibernate.Query)
– Both HQL(Hibernate Query Language) & SQL can be used with Query object.
o Criteria Object
– Criteria object are used to create and execute object oriented criteria queries to retrieve objects.
1
Hibernate Cache Architecture
First Level Cache
Session
Cache Provider
Cache Implementation
(Physical Cache Region)
• A cache helps to keep the current database state available to the application whenever a lookup is performed
or lazy initialization is needed.
• Elements:
1. First-level cache
2. Second-level cache
• Features:
1. Thread safeness: Ensures thread safety by providing a unique set of persistent instances for each
session
1. Non-blocking data access: Provides a continuous data access by avoiding threads in the wait state
throughout an application.
16
• First-Level Cache:
Hibernate Cache Architecture (…)
– First-level cache is always associated with the session object.
– It is active for a single user that handles a database transaction or an application transaction.
– It also maintains the object identity inside a transaction and helps in avoiding database traffic.
– Benefits:
o Can be used with repeated requests for the same instance in a particular session
o Can be used in O/R mapping, which facilitates mapping a database row to a single object. This results in updating
the changes made to the object in the database.
– When the operations such as save() or update() are used on an object or if an object is retrieved using load(), find(),list(),
iterate() or filter() method, then that object is added into session cache.
– evict() method removes the object and its data from the first-level cache.
1
– Session.clear() method completely removes all the objects from the session cache.
• Second-Level Cache:
Hibernate Cache Architecture (…)
– This cache has process scope cache or cluster scope cache.
– The process scope cache stores either the persistent context or persistent state of the processes in a disassembled format.
– The cluster scope cache shares multiple processes on the same machine or between multiple machines in a cluster.
– Configuring cache expiration and physical cache attributes using the cache provider
– While configuring Hibernate in an application, the caching strategy to be used can be defined by implementing the
Hibernate Cache Architecture (…)
• Second-Level Cache: (…)
❑ Caching Strategies: Following can be used in application to retrieve data from the database
• Read-only:
• Data is frequently read but never updated.
• Read/write:
• Data is to be read and update.
• Used in non-JTA env where completion of each transaction should be done before invocation of Session.close()
or Session.disconnect() methods.
• Nonstrict read/write:
• Application sometimes need to update the data along with reading large amount of data.
• This strategy can be used to restrict two or more transactions from modifying the same data simultaneously.
• Transactional: Refers to fully transactional cache that can only be used in JTA 1
Hibernate Cache Architecture (…)
• Second-Level Cache: (…)
❑ Query Cache:
• Hibernate also implements a cache for query resultsets that integrate closely with the second level
cache.
• This is an optional feature and is useful for applications involving few insert, delete or update
operations.
• The query cache caches just the identifier values and not the returned query results.
• Hibernate uses the timestamp cache to decide whether or not the resultset should be cached.
• The most recent resultset obtained by executing the insert, update or delete queries is cached.
• If the timestamp of the resultset query is more than the timestamp of the cached query results, then
the cache results are discarded and a new query is issued. 2
Hibernate Cache Architecture (…)
• Second-Level Cache: (…)
❑ Cache Provider: Open source cache provider that can be used in application are:
▪ ECHCache: Supports read-only, nonstrict read/write and read/write caching strategies. This cache
provider is used for the simple process scope cache in a single JVM. This type of cache provider can be
in memory or on disk.
▪ OpenSymphony cache (OSCache): Enables caching to memory as well as disk in a single JVM with a
query cache. The caching strategy, such as read-only, nonstrict read/write and read/write are supported
by the OSCache cache provider.
▪ Jboss Cache: Refers to fully transactional replicated clustered cache that is based on JGroups, which is a
communication protocol that is purely written in Java and used to create groups of processes whose
members can send messages to each other. It supports read-only and transactional caching strategies.
▪ warmCache: A cluster cache based on JGroups; uses clustered invalidation and doesn’t support
hibernate query cache. 2
Hibernate Mapping Types
• To prepare a Hibernate mapping document, we need to map the Java data types into RDBMS data types.
• The types declared and used in the mapping files are neither Java data types nor SQL database types.
• These types are called Hibernate mapping types, which can translate from Java to SQL data types and vice
versa.
• It is used to convert the datatype supported in object-oriented programming language to a datatype supported by a
database.
• This facilitates the transfer of object-oriented data to the database without the occurrence of an exception due to
incompatibility of datatypes.
• Mappings should be in a format that can define the mapping of the classes with tables, properties with
columns, foreign keys with associations and SQL types with Java types
• It is used to reduce programming code and map the object-oriented programming objects with relational databases
i.e. oracle, DB2, Sybase etc.
• Programming code can be reduced through caching, and by using embedded SQL or call-level interface JDBC
25
Hibernate O/R Mapping (…)
• XML documents are used to define O/R mapping which allows to:
o Use XDoclet support that allows mappings to be generated from javadoc-style source comments
• In complex applications, a problem of class mismatch can occur due to one class inherited by other classes. To
overcome such problems, the following approaches can be used:
o Table-per-class-hierarchy: Removes polymorphism and inheritance relationships completely from relational
model
o Table-per-subclass (normalized mapping)- Denormalizes the relational model and enables polymorphism
26
Hibernate O/R Mapping (…)
• Multiple-objects can be mapped to a single row. Polymorphic associations for the three mapping strategies are as
follows:
o Many-to-one: Serves as an association in which an object reference is mapped to a foreign key association
o One-to-one: Serves as an association in which an object reference is mapped to a primary key or a unique
foreign key association
o Ternary: Serves as an association in which a Map contained and keyed by objects is mapped to a ternary
associations
• Indexes collections such as Maps, Lists and Arrays can be maintained and persisted as key-value pairs. 2
• Mappings are done using persistent class declarations and not by table declarations.
Hibernate O/R Mapping (…)
• Hibernate XML Mapping
Example:
);
28
Hibernate O/R Mapping (…)
• Hibernate XML Mapping
Example:
29
Student_class.java
public class Student_class {
private int id;
private String firstName;
private String lastName;
public Student_class() {}
public Student_class(int id, String fname, String lname)
{
this.id = id;
this.firstName =
fname; this.lastName
= lname;
}
public int getId()
{
return id;
}
public void setId( int id )
{
this.id = id;
} 30
Student_class.java
3
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example:
o <generator> element within the id element 🡪 is used to generate the primary key values automatically.
The class attribute of the generator element is set to native to let hibernate pick up either identity,
sequence, or hilo algorithm to create primary key depending upon the capabilities of the underlying
database. Other values can be: assigned, increment etc.
o <property> element 🡪 is used to map a Java class property to a column in the database table.
The name attribute of the element refers to the property in the class and the column attribute refers to
3
the column in the database table. The type attribute holds the hibernate mapping type.
Hibernate
• Hibernate XML Mapping Example:
O/R Mapping (…)
(…)
3. Hibernate XML Mapping: (…) 🡪Student_class.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate
Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = “Student_class" table = “STUDENT">
<meta attribute = "class-description"> This class contains the student detail. </meta>
<id name = "id" type = "int" column = "id">
<generator class=“assigned"/>
</id>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
</class>
</hibernate-mapping> 3
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example: (…)
o It also requires a set of configuration settings related to database and other related parameters.
o All such information is usually supplied as a standard Java properties file called hibernate.properties,
or as an XML file named hibernate.cfg.xml.
o In XML formatted file, most of the properties take their default values and it is not required to specify
them in the property file unless it is really required.
35
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example: (…)
4. Hibernate Configuration:
🡪hibernate.cfg.xml
Properties Description
Hibernate.dialect This property makes Hibernate generate the appropriate SQL for
the chosen database
Hibernate.connection.driver_class The JDBC driver class.
3
StoreData.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
• 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.
Annotations Purpose
@Entity @Entity is used to mark class as an entity bean, so it must have a no-
argument constructor that is visible with at least protected scope.
@Table @Table annotation allows to specify the details of the table that will be
used to persist the entity in the database.
This 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. 40
Hibernate Annotation (…)
Annotations Purpose
@Id Each entity bean will have a primary key, which can be annotated on the
and class with the @Id annotation.
@GeneratedValue The primary key can be a single field or a combination of multiple fields
depending on table structure.
By default, the @Id annotation will automatically determine the most
appropriate primary key generation strategy to be used but we can
override this by applying the @GeneratedValue annotation, which
takes two parameters strategy and generator.
@Column @Column annotation is used to specify the details of the column to
which a field or property will be mapped. Mostly used attributes are:
o name : permits the name of the column to be explicitly specified
o length: permits the size of the column used
to map a value
particularly for a String value
o nullable: permits the column to be marked NOT NULL when the
schema is generated.
o unique: permits the column to be marked as containing only unique 41
Hibernate Annotation
Student_class.java (…)
import
javax.persistence.*;
@Entity
@Table(name = “STUDENT")
public class Student_class
{
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
public Student_class() {}
public int getId()
{
return id; 4
Hibernate Annotation
Student_class.java (…) (…)
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;
}
}
4
Hibernate Query Language (HQL)
• It is an object oriented extension to SQL that bridges the gap between the object-oriented systems and
relational databases.
• It has a rich and powerful object-oriented query language available with the Hibernate ORM
• HQL queries are case insensitive; however, the names of the Java classes and properties are case sensitive.
• If HQL is used in an application to define a query for a database, the Hibernate framework automatically
generates the SQL query and executes it.
• Unlike SQL, HQL uses classes and properties in lieu of tables and columns.
44
Retrieval using HQL
• HQL can also be used to retrieve objects from database through O/R mapping by performing the
following tasks:
o Use Joins
o Execute subqueries
45
Need of HQL
• HQL perferred over SQL:
o Provides full support for relational operations.
– It is possible to represent SQL queries in the form of objects in HQL, which uses classes and
properties of tables and columns.
– Eliminates the need of explicitly creating objects and populating the data from the ResultSet
retrieved from the execution of a query
– Return the query results along with all the child objects, if any.
4
o Easy to learn and use: Similar to SQL
Need of HQL (…)
• HQL perferred over SQL: (…)
– Supports pagination, fetch join with dynamic profiling, innner/outer/full joins and Cartesian
product.
– It also supports projection, aggregation, grouping , ordering, sub-queries and SQL function calls.
– Helps in writing database independent queries that are converted into native SQL syntax of the
database at run time
4
HQL Syntax
• HQL consists of following elements:
❑ Clauses:
o From
o Select
o Where
o Order by
o Group by
❑ Aggregate functions:
❑ Subqueries:
❑Other 🡪 Pagination using queries:
o Query setFirstResult(int startPosition)
4
o Query setMaxResults(int maxResult)
Clauses in HQL
• Clauses: Clauses are HQL keywords that make up queries. HQL allows to express SQL query in
object- oriented terms e.g. by using classes and their properties.
✔From clause: Specifies the object whose instances are to be returned as a query result
from User
from User as user
✔Where clause: Used to specify a condition based on which the resultset is obtained from a database.
o Syntax: where condition [where condition refers to the combination of logical and
relational operators]
o E.g. To retrieve details of user whose name is
‘Mary’
o E.g. To retrieve user names from the User table order by name in asc and data in desc
✔Group by clause: Used to group properties (returned as query resultset) on a specific criteria.
User.department
o Having clause:
5
Associations and Joins
• Join is used to assign aliases to associated entities or elements of a collection of values.
• Inner join
• Full join
e.g. from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten
5
Aggregate Functions
• Used to perform mathematical operation in a query to retrieve the desired output from the database.
• Functions like:
o Avg(…)
o Sum(…)
o Min(…)
o Max(…)
o Count(…)
• There are four variants:
o Count(*)
o Count(…)
o Count(distinct …)
o Count(all …) 5
Expressions
• Expressions are used with the where clause to extract some rows from the database table. Where clause uses
the following expressions:
• Mathematical operators : +, - , *, /
• String concatenation: ||
• JDBC IN parameters
o Any
o All
o Some
o In
e.g.
From Item item where 100 > all (select b.amount from item.bids b)
import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HQLData {
public static void main(String args[]){
int options,choice=1;
Scanner scan = new Scanner(System.in);
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
HQLData.java
HouseDetails house = new HouseDetails();
while(choice==1){
System.out.println("Enter options: 1.Display all record 2.Insert 3.Update and 4.Delete 5.Search particular record");
options = scan.nextInt();
if(options == 1)
{
System.out.println("Selected option: To display all
records..."); Query query = session.createQuery("from
HouseDetails"); List <HouseDetails>houseList = query.list();
System.out.println("List size "+houseList.size());
for(HouseDetails h:houseList)
{
System.out.println("House No. : "+h.getH_no()+" and House owner name : "+h.getH_owner());
}
}
HQLData.java (…)
else if(options == 2)
{
session.beginTransaction();
System.out.println("Selected option: To insert a record");
System.out.println("Enter house number and owner name: ");
int houseNo = scan.nextInt();
String owner = scan.next();
HouseDetails newhouse = new HouseDetails(houseNo,owner);
session.save(newhouse);
session.getTransaction().commit();
System.out.println("Inserted record...");
}
else if(options == 3)
{
session.beginTransaction();
HQLData.java (…)
System.out.println("Selected option: To update a record");
System.out.println("Enter house number and owner name to update: ");
int houseNo = scan.nextInt();
}
else if(options == 4)
{
session.beginTransaction();
System.out.println("Selected option: To delete a record");
System.out.println("Enter house number to delete: ");
HQLData.java (…)
int houseNo = scan.nextInt();
Query query = session.createQuery("delete from HouseDetails where houseno="+houseNo);
int count = query.executeUpdate(); //session.delete method can also be used
System.out.println(count+" Record Deleted");
session.getTransaction().commit();
}
else if(options == 5)
{
System.out.println("Selected option: To search a record based on house no");
System.out.println("Enter house number: ");
int houseNo = scan.nextInt();
}
session.close();
}
}
Hibernate v/s JDBC
• JDBC is database specific while hibernate works for all databases.
• No knowledge of SQL is needed as hibernate automatically generates HQL queries whereas JDBC
needs SQL.
• Query tuning is not required in hibernate where as in JDBC it needs to be done by database authors.
• In JDBC, Java cache has to be implemented and manually maintained whereas hibernate has cache
architecture
• In JDBC, mapping needs to be additionally coded where as in hibernate it is just an xml file which does all
task.
• Hibernate supports HQL and native SQL whereas JDBC works with SQL only.
11