0% found this document useful (0 votes)
20 views64 pages

Unit 6

Adavance java - be - unit 6

Uploaded by

istra0802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views64 pages

Unit 6

Adavance java - be - unit 6

Uploaded by

istra0802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

ADVANCED JAVA

B.E. – III, Sem. VI


Hibernate 4.0
Contents:

❑ Overview of Hibernate

❑ Hibernate Architecture

❑ Hibernate Mapping Types

❑ Hibernate O/R Mapping

❑ Hibernate Annotation

❑ Hibernate Query Language


Introduction
• Java Database Connectivity (JDBC) provides a set of Java API for accessing the relational databases
from Java program.

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

• Moreover, developers need to provide additional Java code in the


application to handle the
ResultSets containing the data retrieved from the database.

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

• ORM is used to handle this mismatch.

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

• This framework handles mapping from Java classes to database tables


and provides Application
Programming Interface (API) for querying and retrieving data from a database.

• It uses a transparent programming model for this mapping.

• 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. Supports object-oriented programming models : inheritance, polymorphism, composition, abstraction


and the Java collection framework

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.

6. Reduces the development time

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.

9. Provides features: lazy initialization and eager or batch fetching to


improve performance of an
application.
10. Provides integration with Java EE 8
Need of Hibernate (…)
11. Operates transactions in a managed or non-managed environment. It can be outside an application
server container or within standalone applications. This facilitates the following tasks:

✔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

✔JDBC connections may be provided by application data source


✔Hibernate Transaction system integrates with Java EE applications through Java Transaction API
(JTA)

✔Automatic binding of the Hibernate session to the global JTA transaction scope

9
Hibernate
Java Application Architecture
Transient
Layer

Hibernate Framework
Layer
Hibernate
API

Back-end APIs Java EE


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

• Consist of two technologies: Hibernate and Java EE.

• Hibernate make use of existing Java APIs : JDBC, Java Transaction (JTA), JNDI.

• JDBC loads database driver and establishes a connection for accessing relational database.

• It uses all types of database drivers that are supported by Hibernate.

• JNDI and JTA allow Hibernate to be integrated with application servers.

• Hibernate provide various interfaces such as org.hibernate and develop


org.hibernate.cfg to
applications.

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: (…)

o Session (org.hibernate.Session) (…)

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

– Persistent objects are saved and retrieved through a Session object.

o Transaction (org.hibernate.Transaction)

– It’s a single-thread object used by the application to define units of work.

– A transaction is associated with a Session.

– Transactions abstract application code from underlying transaction implementations(JTA/JDBC),


allowing the application to control transaction boundaries via a consistent API. 1
Hibernate Architecture (…)
• Interfaces in Hibernate Framework: (…)

o Transaction (org.hibernate.Transaction) (…)

– It’s an Optional API and application may choose not to use it.

o Query (org.hibernate.Query)

– A single-thread object used to perform query on underlying database.

– A Session is a factory for 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 Concurrency Query


Strategy Cache

Cache Provider

Cache Implementation
(Physical Cache Region)

Second Level Cache


Hibernate Duel-level Cache Architecture 1
Hibernate Cache Architecture (…)
• Hibernate has a dual-level cache architecture.

• 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 is mandatory and cannot be turned off.

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

– flush() method is used to synchronize object with the database.

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

– Insecond-level cache, network communication is very important and requires some


kind of remote process
communication to maintain consistency of the processes among multiple machines.
– Cache policies include caching strategies and physical cache providers, which are used on the basis of various factors,
such as ratio of reads to writes, the size of the database tables, and the number of tables shared with external applications.

– It can be used for mutable and immutable data.

– This level can be implemented by application by following below steps:

– Selecting the concurrency strategy that can be used in the application

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

• Simple and safe to use in cluster.

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

• To enable the query cache, the hibernate.cache.use_query_cache property is set to true.

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

• Date and Time types mapping:


Mapping Type Java Type ANSI SQL Type
date java.util.Date or java.sql.Date DATE
time java.util.Date or java.sql.Time TIME
timestamp java.util.Date or java.sql.Timestamp TIMESTAMP
calendar java.util.Calendar TIMESTAMP
calendar_date java.util.Calendar DATE
22
Hibernate Mapping Types (…)
• Primitive types mapping:
Mapping Type Java Type ANSI SQL Type
integer int or java.lang.Integer INTEGER
long long or java.lang.Long BIGINT
short short or java.lang.Short SMALLINT
float float or java.lang.Float FLOAT
double double or java.lang.Double DOUBLE
big_decimal java.math.BigDecimal NUMERIC
character java.lang.String CHAR(1)
string java.lang.String VARCHAR
byte byte or java.lang.Byte TINYINT
boolean boolean or java.lang.Boolean BIT
23
Hibernate Mapping Types (…)
• Binary and Object types mapping:
Mapping Type Java Type ANSI SQL Type
binary byte[] VARBINARY/BLOB
text java.lang.String CLOB
clob java.sql.Clob CLOB
blob java.sql.Blob BLOB

• JDK related types:


Mapping Type Java Type ANSI SQL Type
class java.lang.Class VARCHAR
locale java.util.Locale VARCHAR
timezone java.util.TimeZone VARCHAR
currency java.util.Currency VARCHAR
24
Hibernate O/R Mapping
• ORM is a technique to map object-oriented data with the relational data.

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

• ORM is also known as O/RM, ORM and O/R mapping.

• 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 Bridge the gap between object-oriented systems and relational databases

o Define the object-relational mapping

o Help to generate and export database table

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

o Table-per-concrete-class: Represents inheritance relationships as foreign key relationships

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-many: Serves as an association in which the collection


of objects is mapped to a foreign key
association
o Many-to-many: Serves as an association in which a collection of objects is transparently mapped to a match
table

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:

1. Student table in RDBMS:


create table STUDENT
(
id INT NOT NULL,
first_name VARCHAR(20) default
NULL, last_name VARCHAR(20)
default NULL, PRIMARY KEY (id)

);

28
Hibernate O/R Mapping (…)
• Hibernate XML Mapping
Example:

1. Student table in RDBMS:


create table STUDENT ( id INT NOT NULL, first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL, PRIMARY KEY (id) );

2. Prepare POJO Class: whose objects will persist in the table


🡪Student_class.java

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

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;
}
}

3
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example:

1. Create Student table in RDBMS:

1. Prepare POJO Class: whose objects will persist in the table


🡪Student_class.java
3. Hibernate XML Mapping: 🡪Student_class.hbm.xml

– Instruct hibernate how to map defined classes to database tables

– Save the mapping file as <ClassName>.hbm.xml

– Mapping elements used in the mapping file are as follows:


o <hibernate-mapping> 🡪 root element, which contains all the <class>elements.

o <class> elements 🡪 Has two attributes. The Java using


class name is specified
the name attribute of the class element and the database tablename is specified using the table
attribute. 3
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example: (…)

3. Hibernate XML Mapping: (…)


o <meta> element 🡪 is optional element and can be used to create the class description.
o <id> element 🡪 maps the unique ID attribute in class to the primary key of the database table. The name
attribute of the id element refers to the property in the class and the column attribute refers to the
column in the database table. The type attribute holds the hibernate mapping type.

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: (…)

4. Hibernate Configuration: 🡪hibernate.cfg.xml


o This file will give information to Hibernate regarding where to find the mapping information that defines
how our Java classes relate to the database tables.

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.

o This file is kept in the root directory of application's classpath.

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.

Hibernate.connection.url The JDBC URL to the database instance.

Hibernate.connection.username The database username.

Hibernate.connection.password The database password.

Hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.


36
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example: (…)

Hibernate Configuration: 🡪hibernate.cfg.xml


<?xml version = "1.0" encoding = "utf-8"?>
4.
<!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 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 = “Student_class.hbm.xml"/>
</session-factory> 7
</hibernate-
Hibernate O/R Mapping (…)
• Hibernate XML Mapping Example: (…)

1. Create Student table in RDBMS:

1. Prepare POJO Class: whose objects will persist in the table


🡪Student_class.java

1. Hibernate XML Mapping: 🡪Student_class.hbm.xml

1. Hibernate Configuration: 🡪hibernate.cfg.xml

1. Create a class that stores the persistent object: 🡪StoreData.java

3
StoreData.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class StoreData {


public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory
factory=cfg.buildSessionFactory(); Session
session=factory.openSession(); Transaction
t=session.beginTransaction(); Student_class
e1=new Student_class(); e1.setId(1);
e1.setFirstName("ABC");
e1.setLastName("XYZ");
session.persist(e1);
t.commit();
session.close();
System.out.println("successfully saved");
}
}
Hibernate Annotation
• Hibernate annotations are the newest way to define mappings without the use of XML file.

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

• HQL is used to execute queries against database.

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

• HQL supports polymorphism as well as associations.

44
Retrieval using HQL
• HQL can also be used to retrieve objects from database through O/R mapping by performing the
following tasks:

o Apply restrictions to properties of objects

o Arrange the results returned by a query by using the order by clause

o Paginate the results

o Aggregate the records by using group by and having clauses

o Use Joins

o Create user-defined functions

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.

o Returns results as objects

– Query results are in form of objects

– These objects can be used to manipulate or retrieve data in an application

– Eliminates the need of explicitly creating objects and populating the data from the ResultSet
retrieved from the execution of a query

o Supports polymorphic queries

– 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: (…)

o Support for advanced features :

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

o Provides database independency

– 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

o Syntax: from object [as object_alias]


o E.g. To retrieve all instances of User

class from mypackage.baseClass.User

from User
from User as user

from User user

o In case of cross join

from User as user, Group as grp


49
Clauses in HQL (…)
✔Select clause: Refers to the objects and properties returned as query resultset.

o Syntax: select [object.property]

o E.g. To retrieve user names from the User table

select user.name from User 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 from User as user where user.name =

‘Mary’

E.g. Inner join :


50
from User user, Document doc where doc.user.name = user.name
Clauses in HQL (…)
✔Order by clause: Used to order (ascending/ descending) the properties of objects that are returned as
query resultset. It is used with select and from clauses.

o Syntax: Order by object1.property1 [asc|desc] [object1.property2]

o E.g. To retrieve user names from the User table order by name in asc and data in desc

From User user order by user.name asc, user.creationDate desc

✔Group by clause: Used to group properties (returned as query resultset) on a specific criteria.

o Syntax: Group by object1.property1,object1.property2


o E.g. To retrieve all user names grouped by department

name select user.name from User user group by

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.

• The join types supported by HQL are as follows:

• Inner join

• Left outer join

• Right outer join

• Full join
e.g. from Cat as cat inner join cat.mate as mate left outer join cat.kittens as kitten

from Cat as cat left join cat.mate.kittens as kittens

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 : +, - , *, /

• Binary comparison operators: =, >=, <=, <>, !=, =

• Logical operators: and, or, not

• String concatenation: ||

• SQL scalar functions: upper() and lower()

• Parenthesis indicate grouping: ()

• In, between, is null

• JDBC IN parameters

• SQL Literals: ‘abc’, 79


5
• Java public static final constants, such as Color.LOBBY
Subqueries
• A query within query is known as subquery and is surrounded by
parenthesis

• Following quantifiers can be used in HQL:

o Any

o All

o Some

o In

e.g.

• Select items where all bids are < 100

From Item item where 100 > all (select b.amount from item.bids b)

• Retrieve the items with bids greater than 100


From Item item where 100 < any ( select b.amount from item.bids b) 5
HQL
Examples
1 String hql = "SELECT SUM(E.salary), E.firstName FROM Employee E GROUP BY E.firstName";
Query query = session.createQuery(hql); //query.setFirstResult(1);
query.setMaxResults(10); List results = query.list();

String hql = "FROM Employee E WHERE E.id = :employee_id";


2
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

3 String hql = "UPDATE Employee set salary = :salary WHERE id = :employee_id";


Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10); int result =
query.executeUpdate();
System.out.println("Rows affected: " + result);

4 String hql = "DELETE FROM Employee WHERE id =


:employee_id"; Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result); 5
Implementing CRUD
Operations using HQL
HQLData.java
import java.util.Iterator;
import java.util.List;

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();

String owner = scan.next();


HouseDetails updatehouse = (HouseDetails) session.get(HouseDetails.class,houseNo);
updatehouse.setH_owner(owner);
session.update(updatehouse);
System.out.println("Record Updated");
session.getTransaction().commit();

}
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();

Query query = session.createQuery("from HouseDetails where houseno="+houseNo);


List <HouseDetails>houseList = query.list();
System.out.println("Total Records Fetched: "+houseList.size());
HQLData.java (…)
for(HouseDetails h:houseList)
{
System.out.println("House owner name : "+h.getH_owner());
}
}
else
{
System.out.println("Enter correct option...");
}
System.out.println("Press 1 to go back to the menu...");
choice = 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

You might also like