0% found this document useful (0 votes)
246 views

Hibernate Architecture

The document provides an overview of the Hibernate architecture and its core classes. It discusses the key components like Configuration, SessionFactory, Session, Transaction, Query, and Criteria objects. It also explains the role of JDBC and why object-relational mapping is used to handle mismatches between object-oriented languages and relational databases.

Uploaded by

rina mahure
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
246 views

Hibernate Architecture

The document provides an overview of the Hibernate architecture and its core classes. It discusses the key components like Configuration, SessionFactory, Session, Transaction, Query, and Criteria objects. It also explains the role of JDBC and why object-relational mapping is used to handle mismatches between object-oriented languages and relational databases.

Uploaded by

rina mahure
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Hibernate Architecture

Prerequisites: Introduction of Hibernate
Hibernate: Hibernate is a framework which is used to develop persistence logic
which is independent of Database software. In JDBC to develop persistence logic
we deal with primitive types. Whereas Hibernate framework we use Objects to
develop persistence logic which are independent of database software.
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.
Following section gives brief description of each of the class objects involved in
Hibernate Application Architecture.

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 two keys components −
 Database Connection − This is handled through one or more
configuration files supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.
 Class Mapping Setup − This component creates the connection between
the Java classes and database tables.
 Configuration is a class which is present in org.hibernate.cfg package. It
activates Hibernate framework. It reads both configuration file and
mapping files.
 It activate Hibernate Framework
 Configuration cfg=new Configuration();
 It read both cfg file and mapping files
 cfg.configure();
 It checks whether the config file is syntactically correct or not.
 If the config file is not valid then it will throw an exception. If it is valid
then it creates a meta-data in memory and returns the meta-data to
object to represent the config file.

SessionFactory Object
Configuration object is used to create a SessionFactory object which in turn
configures Hibernate for the application using the supplied configuration file and
allows for a Session object to be instantiated. The SessionFactory is a thread
safe object and used by all the threads of an application.
The SessionFactory is a heavyweight object; it is usually created during
application start up and kept for later use. You would need one SessionFactory
object per database using a separate configuration file. So, if you are using
multiple databases, then you would have to create multiple SessionFactory
objects.

 SessionFactory is an Interface which is present in org.hibernate package


and it is used to create Session Object.
 It is immutable and thread-safe in nature.
 buildSessionFactory() method gathers the meta-data which is in the cfg
Object.
 From cfg object it takes the JDBC information and create a JDBC
Connection.
SessionFactory factory=cfg.buildSessionFactory();

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.
 Session is an interface which is present in org.hibernate package. Session
object is created based upon SessionFactory object i.e. factory.
 It opens the Connection/Session with Database software through
Hibernate Framework.
 It is a light-weight object and it is not thread-safe.
 Session object is used to perform CRUD operations.
Session session=factory.buildSession();

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.

 Transaction object is used whenever we perform any operation and based


upon that operation there is some change in database.
 Transaction object is used to give the instruction to the database to make
the changes that happen because of operation as a permanent by using
commit() method.
 Transaction tx=session.beginTransaction();
tx.commit();

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.

 Query is an interface that present inside org.hibernate package.


 A Query instance is obtained by calling Session.createQuery().
 This interface exposes some extra functionality beyond that provided by
Session.iterate() and Session.find():
1. A particular page of the result set may be selected by calling
setMaxResults(), setFirstResult().
2. Named query parameters may be used.
Query query=session.createQuery();
Criteria Object
Criteria objects are used to create and execute object oriented criteria queries
to retrieve objects.
 Criteria is a simplified API for retrieving entities by composing Criterion
objects.
 The Session is a factory for Criteria. Criterion instances are usually
obtained via the factory methods on Restrictions.
Criteria criteria=session.createCriteria();

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

Clean and simple SQL processing Complex if it is used in large projects


Good performance with large data Large programming overhead
Very good for small applications No encapsulation
Simple syntax so easy to learn Hard to implement MVC 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. RDBMSs represent data in a tabular
format whereas object-oriented languages, such as Java or C# represent it as an
interconnected graph of objects.
Consider the following Java Class with proper constructors and associated public
function −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}

public int getId() {


return id;
}

public String getFirstName() {


return first_name;
}

public String getLastName() {


return last_name;
}

public int getSalary() {


return salary;
}
}

Consider 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 five mismatch problems −

Sr.No Mismatch & Description


.

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

2
Inheritance
RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-
oriented programming languages.

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

4
Associations
Object-oriented languages represent associations using object references whereas an
RDBMS represents an association as a foreign key column.

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

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 −

Sr.No Advantages
.

1 Let’s business code access objects rather than DB tables.

2 Hides details of SQL queries from OO logic.

3 Based on JDBC 'under the hood.'

4 No need to deal with the database implementation.

5 Entities based on business concepts rather than database structure.

6 Transaction management and automatic key generation.


7 Fast development of application.

An ORM solution consists of the following four entities −

Sr.No Solutions
.

1 An API to perform basic CRUD operations on objects of persistent classes.

2 A language or API to specify queries that refer to classes and properties of classes.

3 A configurable facility for specifying mapping metadata.

4 A technique to interact with transactional objects to perform dirty checking, lazy association
fetching, and other optimization functions.

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

First
nex Hibernate Example without
IDE
Here, we are going to create the first hibernate application without IDE. For creating
the first hibernate application, we need to follow the following steps:

1. Create the Persistent class


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt

1) Create the Persistent class


A simple Persistent class should follow some rules:

o A no-arg constructor: It is recommended that you have a default constructor at


least package visibility so that hibernate can create the instance of the Persistent
class by newInstance() method.
o Provide an identifier property: It is better to assign an attribute as id. This
attribute behaves as a primary key in database.
o Declare getter and setter methods: The Hibernate recognizes the method by
getter and setter method names by default.
o Prefer non-final class: Hibernate uses the concept of proxies, that depends on
the persistent class. The application programmer will not be able to use proxies
for lazy association fetching.

Employee.java
1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String firstName,lastName;  
6.   
7. public int getId() {  
8.     return id;  
9. }  
10. public void setId(int id) {  
11.     this.id = id;  
12. }  
13. public String getFirstName() {  
14.     return firstName;  
15. }  
16. public void setFirstName(String firstName) {  
17.     this.firstName = firstName;  
18. }  
19. public String getLastName() {  
20.     return lastName;  
21. }  
22. public void setLastName(String lastName) {  
23.     this.lastName = lastName;  
24. }  
25.   
26.   
27. }  

2) Create the mapping file for Persistent class


The mapping file name conventionally, should be class_name.hbm.xml. There are many
elements of the mapping file.

o hibernate-mapping : It is the root element in the mapping file that contains all
the mapping elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
o id : It is the subelement of class. It specifies the primary key attribute in the
class.
o generator : It is the sub-element of id. It is used to generate the primary key.
There are many generator classes such as assigned, increment, hilo, sequence,
native etc. We will learn all the generator classes later.
o property : It is the sub-element of class that specifies the property name of the
Persistent class.

Let's see the mapping file for the Employee class:

employee.hbm.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.  "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.  "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.  <hibernate-mapping>  
7.   <class name="com.javatpoint.mypackage.Employee" table="emp1000">  
8.     <id name="id">  
9.      <generator class="assigned"></generator>  
10.     </id>  
11.             
12.     <property name="firstName"></property>  
13.     <property name="lastName"></property>  
14.             
15.   </class>  
16.             
17.  </hibernate-mapping>  
3) Create the Configuration file
The configuration file contains information about the database and mapping file.
Conventionally, its name should be hibernate.cfg.xml .

hibernate.cfg.xml
1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property> 
 
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</
property>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

4) Create the class that retrieves or stores the


object
In this class, we are simply storing the employee object to the database.

1. package com.javatpoint.mypackage;    
2.     
3. import org.hibernate.Session;    
4. import org.hibernate.SessionFactory;    
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11.     
12. public class StoreData {    
13. public static void main(String[] args) {    
14.         
15.     //Create typesafe ServiceRegistry object    
16.     StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configur
e("hibernate.cfg.xml").build();  
17.           
18.    Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
19.   
20. SessionFactory factory = meta.getSessionFactoryBuilder().build();  
21. Session session = factory.openSession();  
22. Transaction t = session.beginTransaction();   
23.             
24.     Employee e1=new Employee();    
25.     e1.setId(101);    
26.     e1.setFirstName("Gaurav");    
27.     e1.setLastName("Chawla");    
28.         
29.     session.save(e1);  
30.     t.commit();  
31.     System.out.println("successfully saved");    
32.     factory.close();  
33.     session.close();    
34.         
35. }    
36. }   

5) Load the jar file


For successfully running the hibernate application, you should have the hibernate5.jar
file.

Download the required jar files for hibernate

6) How to run the first hibernate application


without IDE
We may run this hibernate application by IDE (e.g. Eclipse, Myeclipse, Netbeans etc.) or
without IDE. We will learn about creating hibernate application in Eclipse IDE in next
chapter.
To run the hibernate application without IDE:

o Install the oracle10g for this example.


o Load the jar files for hibernate. (One of the way to load the jar file is copy all the
jar files under the JRE/lib/ext folder). It is better to put these jar files inside the
public and private JRE both.
o Now, run the StoreData class by java com.javatpoint.mypackage.StoreData

HQL | Introduction
Hibernate Query Language (HQL) is an easy to learn and powerful query language designed
as an object-oriented extension to SQL that bridges the gap between the object-oriented
systems and relational databases. The HQL syntax is very similar to the SQL syntax. it has a
rich and powerful object-oriented query language available with the Hibernate ORM, which is
a technique of mapping the objects to the databases. The data from object-oriented systems
are mapped to relational databases with a SQL-based schema.

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it
doesn't depends on the table of the database. Instead of table name, we use class name
in HQL. So it is database independent query language.
HQL can also be used to retrieve objects from database through O/R mapping by performing
the following tasks:

 Apply restrictions to properties of objects


 Arrange the results retuned by a query by using the order by clause
 Paginate the results
 Aggregate the records by using group by and having clauses
 Use Joins
 Create user-defined functions
 Execute subqueries

The Hibernate Query Language, designed as a “minimal” object-oriented extension


to SQL provides an elegant bridge between Java classes and database tables.
Hence it is mandatory to understand the need of HQL in current scenario.
Features of HQL
HQL queries are case insensitive; however, the names of 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, which in turn allows developers to write
queries using less code as compared to SQL. In addition, HQL supports many other
SQL statement and aggregate functions, such as sum() and max() and clauses, such
as group by and order by.
Need of HQL
It is more beneficial to use HQL instead of native SQ retrieve data from databases.
The following are some of the reasons why HQL is preferred over SQL:
 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
instead of tables and columns.
 Return results as objects. In other words, the query results are in the form of
objects rather than the plain text. These objects can be used to manipulate or
retrieve data in an application. This eliminates the need of explicitly creating
objects and populating the data from the resultset retrieved from the execution
of a query.
 Supports polymorphic queries. Polymorphic queries return the query results
along with all the child objects (objects of subclasses), if any.
 Easy to learn and use. The syntax of HQL is quite similar to that of SQL This
makes Hibernate queries easy to learn and implement in the applications.
 Supports many advanced features as compared to SQL, such as pagination,
fetch join with dynamic profiling (initialization the associations or collection of
values with their parent objects can be done using a single select statement),
inner/outer/full joins, and cartesian product. It is also supports projections,
aggregation (max, avg), grouping, ordering, sub queries, and SQL function
calls.
 Provides database independency. HQL helps in writing database independent
queries that are converted into the native SQL syntax of the database at
runtime. This approach helps to use the additional features that the native SQL
query provides.

Advantage of HQL
There are many advantages of HQL. They are as follows:

o database independent
o supports polymorphic queries
o easy to learn for Java Programmer
o
HQL queries
o A query within a query is known as a subquery and is surrounded by
parenthesis. An example of a subquery is subselect in which a select clause
is embedded in another clause, such as select, from and where clause.
Subquery is executed before the execution of the main query.

The query interface provides many methods. There is given commonly used methods:

1. public int executeUpdate() is used to execute the update or delete query.


2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where
record will be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be
retrieved from the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to
the JDBC style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a
named query parameter.
7. Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but
properties like table and column names are case sensitive in HQL.

8. FROM Clause
9. You will use FROM clause if you want to load a complete persistent objects
into memory. Following is the simple syntax of using FROM clause −
10. String hql = "FROM Employee";
11. Query query = session.createQuery(hql);
12. List results = query.list();

13. If you need to fully qualify a class name in HQL, just specify the package and
class name as follows −
14. String hql = "FROM com.hibernatebook.criteria.Employee";
15. Query query = session.createQuery(hql);
16. List results = query.list();

17. AS Clause
18. The AS clause can be used to assign aliases to the classes in your HQL
queries, especially when you have the long queries. For instance, our
previous simple example would be the following −
19. String hql = "FROM Employee AS E";
20. Query query = session.createQuery(hql);
21. List results = query.list();

22. The AS keyword is optional and you can also specify the alias directly after
the class name, as follows −
23. String hql = "FROM Employee E";
24. Query query = session.createQuery(hql);
25. List results = query.list();

26. SELECT Clause


27. The SELECT clause provides more control over the result set then the from
clause. If you want to obtain few properties of objects instead of the complete
object, use the SELECT clause. Following is the simple syntax of using
SELECT clause to get just first_name field of the Employee object −
28. String hql = "SELECT E.firstName FROM Employee E";
29. Query query = session.createQuery(hql);
30. List results = query.list();

31. It is notable here that Employee.firstName is a property of Employee object


rather than a field of the EMPLOYEE table.

32. WHERE Clause


33. If you want to narrow the specific objects that are returned from storage, you
use the WHERE clause. Following is the simple syntax of using WHERE
clause −
34. String hql = "FROM Employee E WHERE E.id = 10";
35. Query query = session.createQuery(hql);
36. List results = query.list();

37. ORDER BY Clause


38. To sort your HQL query's results, you will need to use the ORDER BY clause.
You can order the results by any property on the objects in the result set
either ascending (ASC) or descending (DESC). Following is the simple syntax
of using ORDER BY clause −
39. String hql = "FROM Employee E WHERE E.id > 10 ORDER BY
E.salary DESC";
40. Query query = session.createQuery(hql);
41. List results = query.list();
42. If you wanted to sort by more than one property, you would just add the
additional properties to the end of the order by clause, separated by commas
as follows −
43. String hql = "FROM Employee E WHERE E.id > 10 " +
44. "ORDER BY E.firstName DESC, E.salary DESC ";
45. Query query = session.createQuery(hql);
46. List results = query.list();

47. GROUP BY Clause


48. This clause lets Hibernate pull information from the database and group it
based on a value of an attribute and, typically, use the result to include an
aggregate value. Following is the simple syntax of using GROUP BY clause −
49. String hql = "SELECT SUM(E.salary), E.firtName FROM
Employee E " +
50. "GROUP BY E.firstName";
51. Query query = session.createQuery(hql);
52. List results = query.list();

53. Using Named Parameters


54. Hibernate supports named parameters in its HQL queries. This makes writing
HQL queries that accept input from the user easy and you do not have to
defend against SQL injection attacks. Following is the simple syntax of using
named parameters −
55. String hql = "FROM Employee E WHERE E.id = :employee_id";
56. Query query = session.createQuery(hql);
57. query.setParameter("employee_id",10);
58. List results = query.list();

59. UPDATE Clause


60. Bulk updates are new to HQL with Hibernate 3, and delete work differently in
Hibernate 3 than they did in Hibernate 2. The Query interface now contains a
method called executeUpdate() for executing HQL UPDATE or DELETE
statements.
61. The UPDATE clause can be used to update one or more properties of an one
or more objects. Following is the simple syntax of using UPDATE clause −
62. String hql = "UPDATE Employee set salary = :salary " +
63. "WHERE id = :employee_id";
64. Query query = session.createQuery(hql);
65. query.setParameter("salary", 1000);
66. query.setParameter("employee_id", 10);
67. int result = query.executeUpdate();
68. System.out.println("Rows affected: " + result);

69. DELETE Clause


70. The DELETE clause can be used to delete one or more objects. Following is
the simple syntax of using DELETE clause −
71. String hql = "DELETE FROM Employee " +
72. "WHERE id = :employee_id";
73. Query query = session.createQuery(hql);
74. query.setParameter("employee_id", 10);
75. int result = query.executeUpdate();
76. System.out.println("Rows affected: " + result);

77. INSERT Clause


78. HQL supports INSERT INTO clause only where records can be inserted from
one object to another object. Following is the simple syntax of using INSERT
INTO clause −
79. String hql = "INSERT INTO Employee(firstName, lastName,
salary)" +
80. "SELECT firstName, lastName, salary FROM
old_employee";
81. Query query = session.createQuery(hql);
82. int result = query.executeUpdate();
83. System.out.println("Rows affected: " + result);

84. Aggregate Methods


85. HQL supports a range of aggregate methods, similar to SQL. They work the
same way in HQL as in SQL and following is the list of the available functions

Sr.No Functions & Description


.

1
avg(property name)
The average of a property's value

2
count(property name or *)
The number of times a property occurs in the results

3
max(property name)
The maximum value of the property values

4
min(property name)
The minimum value of the property values

5
sum(property name)
The sum total of the property values
86. The distinct keyword only counts the unique values in the row set. The
following query will return only unique count −
87. String hql = "SELECT count(distinct E.firstName) FROM
Employee E";
88. Query query = session.createQuery(hql);
89. List results = query.list();

90. Pagination using Query


91. There are two methods of the Query interface for pagination.

Sr.No Method & Description


.

1
Query setFirstResult(int startPosition)
This method takes an integer that represents the first row in your result set, starting with row
0.

2
Query setMaxResults(int maxResult)
This method tells Hibernate to retrieve a fixed number maxResults of objects.

92. Using above two methods together, we can construct a paging component in
our web or Swing application. Following is the example, which you can
extend to fetch 10 rows at a time −
93. String hql = "FROM Employee";
94. Query query = session.createQuery(hql);
95. query.setFirstResult(1);
96. query.setMaxResults(10);
97. List results = query.list();

You might also like