0% found this document useful (0 votes)
228 views60 pages

Adv - Java GTU Study Material Presentations Unit-6 Hibernate 4.0

This document provides an overview of the Hibernate unit, which covers object-relational mapping using Hibernate. It discusses the key components of the Hibernate architecture, including the configuration, session factory, session, transaction, query, and criteria objects. The configuration object establishes the database connection and class mappings. The session factory is thread-safe and used to configure Hibernate. Sessions provide a connection to perform CRUD operations, while transactions represent a unit of work with the database. Queries and criteria are used to retrieve data and create objects.

Uploaded by

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

Adv - Java GTU Study Material Presentations Unit-6 Hibernate 4.0

This document provides an overview of the Hibernate unit, which covers object-relational mapping using Hibernate. It discusses the key components of the Hibernate architecture, including the configuration, session factory, session, transaction, query, and criteria objects. The configuration object establishes the database connection and class mappings. The session factory is thread-safe and used to configure Hibernate. Sessions provide a connection to perform CRUD operations, while transactions represent a unit of work with the database. Queries and criteria are used to retrieve data and create objects.

Uploaded by

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

2160707

Advanced Java

Unit-6
Hibernate

Prof. Swati R. Sharma


[email protected]
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

Reference Book:
Black Book “ Java server programming” J2EE, 1st ed., Dream Tech Publishers,
2008. 3. Kathy walrath ”
Chapter 15

Unit-6 Hibernate 2 Darshan Institute of Engineering & Technology


Hibernate: Introduction
 Hibernate is used to convert object data in JAVA to relational
database tables.
 It is an open source Object-Relational Mapping (ORM) for Java.

 Hibernate is responsible for making data persistent by storing it in


a database.

Unit-6 Hibernate 3 Darshan Institute of Engineering & Technology


Object-Relational Mapping (ORM)
 It is a programming technique for converting object-type data of
an object oriented programming language into database tables.
 Hibernate is used to convert object data in JAVA to relational
database tables.

Unit-6 Hibernate 4 Darshan Institute of Engineering & Technology


JDBC v/s Hibernate
JDBC Hibernate
JDBC maps Java classes to database Hibernate automatically generates the
tables (and from Java data types to SQL queries.
data types)
With JDBC, developer has to write code Hibernate is flexible and powerful ORM
to map an object model's data to a to map Java classes to database tables.
relational data model.
With JDBC, it is developer’s Hibernate reduces lines of code by
responsibility to handle JDBC result set maintaining object-table mapping itself
and convert it to Java. So with JDBC, and returns result to application in form
mapping between Java objects and of Java objects, hence reducing the
database tables is done manually. development time and maintenance
cost.

Unit-6 Hibernate 5 Darshan Institute of Engineering & Technology


JDBC vs Hibernate
JDBC Hibernate
Require JDBC Driver for different types Makes an application portable to all SQL
of database. databases.
Handles all create-read-update-delete Handles all create-read-update-delete
(CRUD) operations using SQL Queries. (CRUD) operations using simple API; no
SQL
Working with both Object-Oriented Hibernate itself takes care of this
software and Relational Database is mapping using XML files so developer
complicated task with JDBC. does not need to write code for this.
JDBC supports only native Structured Hibernate provides a powerful query
Query Language (SQL) language Hibernate Query Language-
HQL (independent from type of
database)

Unit-6 Hibernate 6 Darshan Institute of Engineering & Technology


Overview of Hibernate

7
Unit-4 Java Server Pages(JSP) 7 Darshan Institute of Engineering & Technology
Hibernate Framework
 Hibernate framework simplifies the development of java
application to interact with the database.
 Hibernate is an open source, lightweight, ORM (Object Relational
Mapping) tool.
 An ORM tool simplifies the data creation, data manipulation and
data access.
 Hibernate is a programming technique that maps the object to the
data stored in the database.

Unit-6 Hibernate 8 Darshan Institute of Engineering & Technology


Hibernate Framework

Java
Object ORM Database
Application

The ORM tool internally uses


the JDBC API to interact with
the database.

Unit-6 Hibernate 9 Darshan Institute of Engineering & Technology


Hibernate Architecture
 There are 4 layers in hibernate Application
architecture
1. Java application layer Persistent
2. Hibernate framework layer Object

3. Backend API layer


4. Database layer. HIBERNATE

Mapping File

Configuration File

Database

Unit-6 Hibernate 10 Darshan Institute of Engineering & Technology


Hibernate Architecture
Java Application

Persistent Object

Core object
Hibernate
of Hibernate
Framework
Configuration Session Factory Session

Transaction Query Criteria

JTA JDBC JNDI


Internal API
Database used by
Hibernate

Unit-6 Hibernate 11 Darshan Institute of Engineering & Technology


Hibernate Architecture
What do you mean by Persistence?

Persistence simply means that we would like our application’s data to


outlive the applications process. In Java terms, we would like the
state of (some of) our objects to live beyond the scope of the JVM so
that the same state is available later.

Unit-6 Hibernate 12 Darshan Institute of Engineering & Technology


Hibernate Architecture
Internal API used by Hibernate
1. JDBC (Java Database Connectivity)
2. JTA (Java Transaction API)
3. JNDI (Java Naming Directory Interface)

https://www.youtube.com/watch?v=hfv9ZXUzjhk

Unit-6 Hibernate 13 Darshan Institute of Engineering & Technology


Hibernate Architecture
 For creating the first hibernate application, we must know the
objects/elements of Hibernate architecture.
 They are as follows:
1. Configuration
2. Session factory
3. Session
4. Transaction factory
5. Query
6. Criteria

Unit-6 Hibernate 14 Darshan Institute of Engineering & Technology


Hibernate Architecture
[1] 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.
 The Configuration object provides two 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.

Unit-6 Hibernate 15 Darshan Institute of Engineering & Technology


Hibernate Architecture
[2] SessionFactory Object
 The SessionFactory is a thread safe object and used by all the
threads of an application.
 Configuration object is used to create a SessionFactory object
which in turn configures Hibernate for the application.
 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.

Unit-6 Hibernate 16 Darshan Institute of Engineering & Technology


Hibernate Architecture
[3] 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.
 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 as needed.

Unit-6 Hibernate 17 Darshan Institute of Engineering & Technology


Hibernate Architecture
[4] 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).

Unit-6 Hibernate 18 Darshan Institute of Engineering & Technology


Hibernate Architecture
[5] 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.

Unit-6 Hibernate 19 Darshan Institute of Engineering & Technology


Hibernate Architecture
[6] Criteria Object

Criteria objects are used to create and execute object oriented


criteria queries to retrieve objects.

Unit-6 Hibernate 20 Darshan Institute of Engineering & Technology


Hibernate Cache Architecture
Known as Session Cache.
Database
Session cache is a mandatory
cache through which all
requests must pass through. 

First-level Cache
Hibernate

Session Object Client

Mainly responsible for


caching objects across Second-level Cache
sessions.
Optional Cache

Unit-6 Hibernate 21 Darshan Institute of Engineering & Technology


Why Cache Architecture?
 Caching is all about application performance optimization.
 It is situated between your application and the database to avoid
the number of database hits as many as possible.
 To give a better performance for critical applications.

Unit-6 Hibernate 22 Darshan Institute of Engineering & Technology


Hibernate Cache Architecture
First-level cache:
 The first-level cache is the Session cache.

 The Session object keeps an object under its own control before
committing it to the database.
 If you issue multiple updates to an object, Hibernate tries to delay
doing the update as long as possible to reduce the number of
update SQL statements issued.
 If you close the session, all the objects being cached are lost.

Unit-6 Hibernate 23 Darshan Institute of Engineering & Technology


Hibernate Cache Architecture
Second-level cache:
 It is responsible for caching objects across sessions.

 Second level cache is an optional cache and first-level cache will


always be consulted before any attempt is made to locate an
object in the second-level cache.
 Any third-party cache can be used with Hibernate.
An org.hibernate.cache.CacheProvider interface is provided,
which must be implemented to provide Hibernate with a handle
to the cache implementation.

Unit-6 Hibernate 24 Darshan Institute of Engineering & Technology


Hibernate Mapping Types
 While preparing a Hibernate mapping document, we map the Java
data types into RDBMS data types.
 The types declared and used in the mapping files are not Java data
types; they are not SQL database types either.
 These types are called Hibernate mapping types, which can
translate from Java to SQL data types and vice versa.

Unit-6 Hibernate 25 Darshan Institute of Engineering & Technology


Hibernate Mapping Types:
Primitive Types
Mapping type Java type 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
character java.lang.String CHAR(1)
byte byte TINYINT
boolean boolean BIT
true/false boolean CHAR(1) ('T' or 'F')

Unit-6 Hibernate 26 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping
Three most important mapping are as follows:
1. Collections Mappings
2. Association Mappings
3. Component Mappings

Unit-6 Hibernate 30 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping
Collections Mappings
 If an entity or class has collection of values for a particular
variable, then we can map those values using any one of the
collection interfaces available in java.
 Hibernate can persist instances of java.util.Map, java.util.Set,
java.util.SortedMap, java.util.SortedSet, java.util.List, and
any array of persistent entities or values.

Unit-6 Hibernate 31 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping:
Collection type Mapping and Description
java.util.Set This is mapped with a <set> element and initialized
with java.util.HashSet
java.util.SortedSet This is mapped with a <set> element. The sort attribute
can be set to either a comparator or natural ordering.

java.util.List This is mapped with a <list> element and initialized


with java.util.ArrayList

java.util.Collection This is mapped with a <bag> or <ibag> element and


initialized with java.util.ArrayList
java.util.Map This is mapped with a <map> element and initialized
with java.util.HashMap
java.util.SortedMap This is mapped with a <map> element.
The sort attribute can be set to either a comparator or
natural ordering.

Unit-6 Hibernate 32 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping:
Association Mappings:
 The mapping of associations between entity classes and the
relationships between tables is the soul of ORM.
 There are the four ways in which the cardinality of the relationship
between the objects can be expressed.
 An association mapping can be unidirectional as well as
bidirectional.

Unit-6 Hibernate 33 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping:
Association Mappings:
Mapping type Description
Many-to-One Mapping many-to-one relationship using Hibernate
One-to-One Mapping one-to-one relationship using Hibernate
One-to-Many Mapping one-to-many relationship using Hibernate
Many-to-Many Mapping many-to-many relationship using Hibernate

Unit-6 Hibernate 34 Darshan Institute of Engineering & Technology


Hibernate O/R Mapping:
Component Mappings:
 If the referred class does not have it's own life cycle and
completely depends on the life cycle of the owning entity class,
then the referred class hence therefore is called as the
Component class.
 The mapping of Collection of Components is also possible in a
similar way just as the mapping of regular Collections with minor
configuration differences. 
Mapping type Description
Component Mapping for a class having a reference to another class as a
Mappings member variable.

Unit-6 Hibernate 35 Darshan Institute of Engineering & Technology


Advantages of Hibernate Framework
1. Open source and Lightweight: Hibernate framework is open
source under the LGPL (GNU Lesser General Public License ) 
license and lightweight.
2. Fast performance: The performance of hibernate framework is
fast because cache is internally used in hibernate framework.
3. Database Independent query: HQL (Hibernate Query Language)
is the object-oriented version of SQL. It generates the database
independent queries. So you don't need to write database
specific queries. Before Hibernate, if database is changed for the
project, we need to change the SQL query as well that leads to
the maintenance problem.

Unit-6 Hibernate 36 Darshan Institute of Engineering & Technology


Advantages of Hibernate Framework
4. Automatic table creation: Hibernate framework provides the
facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.
5. Simplifies complex join: To fetch data from multiple tables is easy
in hibernate framework.
6. Provides query statistics and database status: Hibernate
supports Query cache and provide statistics about query and
database status.

Unit-6 Hibernate 37 Darshan Institute of Engineering & Technology


Hibernate Query Language (HQL)
 The Hibernate ORM framework provides its own query language
called Hibernate Query Language .
 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.
Therefore, it is database independent query language.

Unit-6 Hibernate 38 Darshan Institute of Engineering & Technology


Hibernate Query Language (HQL)
Characteristics of HQL
1. Similar to SQL
HQL’s syntax is very similar to standard SQL. If you are familiar
with SQL then writing HQL would be pretty easy.
2. Fully object-oriented: HQL doesn’t use real names of table and
columns. It uses class and property names instead. HQL can
understand inheritance, polymorphism and association.
3. Reduces the size of queries

Unit-6 Hibernate 39 Darshan Institute of Engineering & Technology


HQL vs SQL
SELECT QUERY

SQL
ResultSet rs=st.executeQuery("select * from diet");
HQL
Query query= session.createQuery("from diet");
//here persistent class name is diet 

Unit-6 Hibernate 40 Darshan Institute of Engineering & Technology


HQL vs SQL
SELECT with WHERE clause

SQL
ResultSet rs=st.executeQuery("select * from diet where id=301");
HQL
Query query= session.createQuery("from diet where id=301 ");
//here persistent class name is diet 

Unit-6 Hibernate 41 Darshan Institute of Engineering & Technology


HQL vs SQL
UPDATE QUERY
SQL
1. String query = "update User set name=? where id = ?";
2. PreparedStatement preparedStmt = conn.prepareStatement(query);
3. preparedStmt.setString (1, “DIET_CE”);
4. preparedStmt.setInt(2, 054);
5. preparedStmt.executeUpdate();
HQL
6. Query q=session.createQuery("update User set name=:n where id=:i");
7. q.setParameter("n", "DIET_CE");  
8. q.setParameter("i",054);  
9. int status=q.executeUpdate(); 
 

Unit-6 Hibernate 42 Darshan Institute of Engineering & Technology


HQL vs SQL
INSERT QUERY

SQL
String sql = "INSERT INTO Stock VALUES (100, 'abc')";
int result = stmt.executeUpdate(sql);

HQL
Query query = session.createQuery("insert into Stock(stock_code,
stock_name) select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

Unit-6 Hibernate 43 Darshan Institute of Engineering & Technology


Steps to run hibernate example
Steps to run first hibernate example with MySQL in Netbeans IDE 8.2
Step-1:  Create the database
CREATE DATABASE retailer;
Step-2: Create table result
CREATE TABLE customers(
name varchar(20),
C_ID int NOT NULL AUTO_INCREMENT,
address varchar(20),
email varchar(50),
PRIMARY KEY(C_ID)
);
Unit-6 Hibernate 44 Darshan Institute of Engineering & Technology
Steps to run hibernate example
Step-3: Create new java application.
 File > New project > Java > Java Application > Next
Name it as HibernateTest.
 Then click Finish to create the project.

Unit-6 Hibernate 45 Darshan Institute of Engineering & Technology


Steps to run hibernate example
Step-4: Create a POJO(Plain Old Java Objects)  class
 We create this class to use variables to map with the database
columns.
 Right click the package (hibernatetest) & select New > Java Class
Name it as Customer.
 Click Finish to create the class.

Unit-6 Hibernate 46 Darshan Institute of Engineering & Technology


Steps to run hibernate example: Step-4
1. package hibernatetest;
2. public class Customer {
3. public String customerName;
4. public int customerID;
5. public String customerAddress;
6. public String customerEmail;
7. public void setCustomerAddress(String
customerAddress) {
this.customerAddress = customerAddress;}
8. public void setCustomerEmail(String customerEmail) {
9. this.customerEmail = customerEmail;}
10.public void setCustomerID(int customerID) {
11. this.customerID = customerID; }

Unit-6 Hibernate 47 Darshan Institute of Engineering & Technology


Steps to run hibernate example: Step-4
12. public void setCustomerName(String customerName) {
13. this.customerName = customerName; }
14. public String getCustomerAddress() {
15. return customerAddress; }
16. public String getCustomerEmail() {
17. return customerEmail; }
18. public int getCustomerID() {
19. return customerID; }
20. public String getCustomerName() {
21. return customerName; }
22.}

Unit-6 Hibernate 48 Darshan Institute of Engineering & Technology


Steps to run hibernate example: Step-4
Step-4: Create a POJO(Plain Old Java Objects)  class
 To generate getters and setters easily in NetBeans, right click on the
code and select Insert Code Then choose Getter... or Setter...
 Variable customerName will map with the name column of the
customers table.
 Variable customerID will map with the C_ID column of the
customers table. It is integer & auto incremented. So POJO class
variable also should be int.
 Variable customerAddress will map with the address column of the
customers table.
 Variable customerEmail will map with the email column of the
customers table.
Unit-6 Hibernate 49 Darshan Institute of Engineering & Technology
Steps to run hibernate example
Step-5: Connect to the database we have already created. [retailer]
 Select Services tab lying next to the Projects tab.
 Expand Databases.
 Expand MySQL Server. There we can see the all databases on
MySQL sever
 Right click the database retailer. Select Connect.

Unit-6 Hibernate 50 Darshan Institute of Engineering & Technology


Steps to run hibernate example
Step-6: Creating the configuration XML
 Hibernate need a configuration file to create the connection.
 Right click package hibernatetest select New > Other > Hibernate
> Hibernate Configuration Wizard  
 Click Next >
 In next window click the drop down menu of Database
Connection and select retailer database connection.

Unit-6 Hibernate 51 Darshan Institute of Engineering & Technology


Steps to run hibernate example: Step-6
Step-6: Creating the configuration XML

 Click Finish to create the file.


Unit-6 Hibernate 52 Darshan Institute of Engineering & Technology
Steps to run hibernate example
1. <hibernate-configuration> hibernate.cfg.xml
2. <session-factory>
3. <property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver </property>
4. <property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/retailer</property>
5. <property name="hibernate.connection.username">
root</property>
6. <property name="hibernate.connection.password">
root</property>
7. <property name="hibernate.connection.pool_size">
10</property>
8. <property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect</property>

Unit-6 Hibernate 53 Darshan Institute of Engineering & Technology


Steps to run hibernate example
9. <property name="current_session_context_class">
thread</property>
10.<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>
11.<property name="show_sql">true</property>
12.<property name="hibernate.hbm2ddl.auto">
update</property>
13.<mapping resource="hibernate.hbm.xml"></mapping>
14.</session-factory>
15.</hibernate-configuration>

Unit-6 Hibernate 54 Darshan Institute of Engineering & Technology


Steps to run hibernate example
Step-7:  Creating the mapping file [hibernate.hbm]
 Mapping file will map relevant java object with relevant database
table column.
 Right click project select New > Other > Hibernate > Hibernate
Mapping Wizard  
 click Next name it as hibernate.hbm 
 click Next> In next window we have to select Class to Map and
Database Table.
 After selecting correct class click OK
Select Database Table
Click drop down list and select the table you want to map.
Code for mapping file.
Unit-6 Hibernate 55 Darshan Institute of Engineering & Technology
Steps to run hibernate example: Step-7
1. <hibernate-mapping>
2. <class name="hibernatetest.Customer" table="customers">
3. <id column="C_ID" name="customerID" type="int">
4. <generator class="native">
5. </generator></id>
6. <property name="customerName">
7. <column name="name">
8. </column></property>
9. <property name="customerAddress">
10. <column name="address">
11. </column></property>
12. <property name="customerEmail">
13. <column name="email">
hibernate.hbm.xml
14. </column></property>
15. </class></hibernate-mapping>
Unit-6 Hibernate 56 Darshan Institute of Engineering & Technology
Steps to run hibernate example: Step-7
Step-7:  Creating the mapping file [hibernate.hbm]
 property name = variable name of the POJO class
 column name = database column that maps with previous variable

Unit-6 Hibernate 57 Darshan Institute of Engineering & Technology


Steps to run hibernate example
Step-8: Now java program to insert record into the database
1. package hibernatetest;
2. import org.hibernate.Session;
3. import org.hibernate.SessionFactory;
4. public class HibernateTest {
5. public static void main(String[] args) {
6. Session session = null;
7. try
8. {
9. SessionFactory sessionFactory = new
org.hibernate.cfg.Configuration().configure().buildSessi
onFactory();

Unit-6 Hibernate 58 Darshan Institute of Engineering & Technology


Steps to run hibernate example
10.session =sessionFactory.openSession();
11. session.beginTransaction();
12. System.out.println("Populating the database !");
13. Customer customer = new Customer();
14. customer.setCustomerName("DietCX");
15. customer.setCustomerAddress("DIET,Hadala");
16. customer.setCustomerEmail("[email protected]");
17. session.save(customer);
18. session.getTransaction().commit();
19. System.out.println("Done!");
20. session.flush();
21. session.close();
22. }catch(Exception e)
{System.out.println(e.getMessage()); } } }

Unit-6 Hibernate 59 Darshan Institute of Engineering & Technology


Steps to run hibernate example:output

Unit-6 Hibernate 60 Darshan Institute of Engineering & Technology


Steps to run hibernate example: output

Unit-6 Hibernate 61 Darshan Institute of Engineering & Technology


Hibernate Program Hierarchy

Unit-6 Hibernate 62 Darshan Institute of Engineering & Technology


GTU Questions
1 Explain the Hibernate cache architecture.
2 What is HQL? How does it different from SQL? List its advantages.
3 What is OR mapping? Give an example of Hibernate XML mapping file.
4 What is HQL? How does it differ from SQL? Give its advantages.
5 Draw and explain the architecture of Hibernate.
6 Explain architecture of Hibernate.
7 Explain architecture of Spring MVC Framework. Explain all modules in brief.

8 What is O/R Mapping? How it is implemented using Hibernate. Explain with


example.
9 What are the advantages of Hibernate over JDBC?
10 What is hibernate? List the advantages of hibernate over JDBC.

11 Develop program to get all students data from database using hibernate. Write
necessary xml files.

Unit-6 Hibernate 65 Darshan Institute of Engineering & Technology

You might also like