Chapter 02 - Hibernate Architecture - Configuration - Mapping
Chapter 02 - Hibernate Architecture - Configuration - Mapping
Configuration
Objectives
◆ Understand ORM: Grasp the core concepts and benefits of object-
relational mapping.
◆ Map Entities: Efficiently map Java classes to database tables and manage
relationships.
◆ Control Transactions: Ensure data integrity with transactions and concurrecy
handling.
◆ Integrate with Spring: Leverage Spring Framework for dependency injection
and simplified data access.
◆ Gain Practical Experience: Build projects and experiment with advanced
features.
2
Contents
Introduction
Key Concepts
Annotations
Relationships
Using Hibernate
Demo
Advantages and Disadvantages
3
What is Hibernate ?
◆ Hibernate is a powerful object-relational mapping (ORM) framework for the
Java programming language.
◆ It acts as a bridge between the object-oriented world of Java and the
relational world of databases, making it easier for developers to work with
persistent data.
◆ Hibernate simplifies Java persistence, allowing developers to focus
on the business logic of their applications rather than the intricacies of
database interactions.
4
Key Features of Hibernate
◆ ORM: Maps Java objects to relational database tables, simplifying data access.
◆ JPA Implementation: Adheres to the JPA standard, ensuring portability and
flexibility.
◆ HQL (Hibernate Query Language): Powerful object-oriented query language
for retrieving and manipulating data.
◆ Lazy Loading: Loads associated data on demand, minimizing data transfer
and enhancing responsiveness.
◆ Transaction Management: Ensures data consistency and integrity through
transaction support.
◆ Inheritance Mapping: Handles various inheritance scenarios, mapping Java
class hierarchies to database tables.
5
Benefits of Using Hibernate
◆ Faster Development: Spend less time on database code, more time on logic
features
◆ Cleaner Code: Write concise, object-oriented code instead of complex SQL.
◆ Improved Maintainability: Easier to understand, update, and refactor your cod
ebase.
◆ Database Flexibility: Switch between different databases without major code
changes.
6
Benefits of Using Hibernate
◆ Performance Boost: Caching and lazy loading optimize data access for faster
applications.
◆ Data Integrity: Built-in mechanisms ensure data consistency and
prevent errors.
◆ Industry Standard: Widely used in the Java ecosystem, making you job-ready.
◆ Spring Integration: Works seamlessly with Spring, the leading Java framework
.
7
Hibernate Architecture
8
Hibernate Architecture
Session Factory: Manages configuration and creates Sessions
Session: Provides data access methods and interacts with persistent object
Persistent Objects: Java objects representing data stored in the database.
Transaction Management: Ensures data consistency and integrity.
Connection Provider: Handles database connections and pooling.
Query API: Supports HQL, Criteria API, and native SQL for flexible querying
Caching: Optimizes performance with first-level and second-level caches.
Event System: Allows customization of persistence lifecycle events.
Dialects: Generates database-specific SQL for portability.
9
Hibernate Architecture
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider.
It holds second level cache (optional) of data.
The org.hibernate.SessionFactory interface provides factory method to get
the object of Session.
Session
The session object provides an interface between the application and data
stored in the database. It is a short-lived object and wraps the JDBC
connection. It is factory of Transaction, Query and Criteria. It holds a first-level
cache (mandatory) of data.
The org.hibernate.Session interface provides methods to insert, update and
delete the object. It also provides factory methods for Transaction, Query and
Criteria.
10
Hibernate Architecture
Transaction
The transaction object specifies the atomic unit of work. It is optional.
The org.hibernate.Transaction interface provides methods for transaction
management.
ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from
DriverManager or DataSource. It is optional.
TransactionFactory
It is a factory of Transaction. It is optional.
11
Hibernate Lifecycle
12
Hibernate Lifecycle
◆ The Hibernate lifecycle refers to the various states an entity instance goes
through during its interaction with the persistence framework. Understanding
this lifecycle is crucial for effectively managing data and ensuring data
integrity in your applications.
13
Hibernate Lifecycle
1. Transient State
An entity instance is in a transient state when it's newly created using
the new operator and not yet associated with a Hibernate session.
Changes made to a transient instance are not tracked by Hibernate and
won't be persisted to the database.
14
Hibernate Lifecycle
2. Persistent State
◆ An entity instance transitions to the persistent state when it's associated with a
Hibernate session. This can happen through:
persist() method: Explicitly makes an instance persistent.
Cascading: If an associated entity is persisted and cascading is enabled,
the current instance becomes persistent as well.
Querying: When an entity is retrieved from the database using find(), createQuery(), or oth
er query methods.
◆ Changes made to a persistent instance are tracked by Hibernate and will be synchronized wit
h the database upon flushing or transaction commit.
15
Hibernate Lifecycle
3. Detached State
◆ An entity instance becomes detached when it's no longer associated with a
Hibernate session. This can occur when:
Session is closed: Closing the session detaches all persistent instances asso
ciated with it.
detach() method: Explicitly detaches an instance from the session.
Serialization: Serializing a persistent instance detaches it.
◆ Changes made to a detached instance are not tracked by Hibernate and won't be
automatically persisted.
16
Hibernate Lifecycle
4. Removed State
◆ An entity instance enters the removed state when it's marked for deletion
commit.
17
JPA vs Hibernate
JPA Hibernate
Java Persistence API (JP.A) defines the management of Hibernate is an Object-Relational Mapping (ORM) tool which is
relational data in the Java applications. used to save the state of Java object into the database.
It is just a specification. Various ORM tools implement it for data It is one of the most frequently used JPA implementation.
persistence.
It is defined in javax.persistence package. It is defined in org.hibernate package.
The EntityManagerFactory interface is used to interact with the It uses SessionFactory interface to create Session instances.
entity manager factory for the persistence unit. Thus, it provides
an entity manager.
It uses EntityManager interface to create, read, and delete It uses Session interface to create, read, and delete operations
operations for instances of mapped entity classes. This interface for instances of mapped entity classes. It behaves as a runtime
interacts with the persistence context. interface between a Java application and Hibernate.
It uses Java Persistence Query Language (JPQL) as an It uses Hibernate Query Language (HQL) as an object-oriented
object-oriented query language to perform database operations. query language to perform database operations.
18
Hibernate Configuration
As Hibernate can operate in different environments, it requires a wide range of
configuration parameters. These configurations contain the mapping
information that provides different functionalities to Java classes. Generally, we
provide database related mappings in the configuration file. Hibernate
facilitates to provide the configurations either in an XML file (like
hibernate.cfg.xml) or properties file (like hibernate.properties).
19
Properties of Hibernate Configuration
◆ Hibernate JDBC Properties
Property Description
20
Properties of Hibernate Configuration
◆ Hibernate Datasource Properties
Property Description
21
Properties of Hibernate Configuration
Property Description
hibernate.dialect It represents the type of database used in hibernate to generate SQL
statements for a particular relational database.
hibernate.show_sql It is used to display the executed SQL statements to console.
22
Properties of Hibernate Configuration
Property Description
hibernate.default_entity_mode It sets a default mode for entity representation for all sessions
opened from this SessionFactory
hibernate.order_updates It orders SQL updates on the basis of the updated primary key.
hibernate.use_identifier_rollback If enabled, the generated identifier properties will be reset to default
values when objects are deleted.
hibernate.generate_statistics If enabled, the Hibernate will collect statistics useful for
performance tuning.
hibernate.use_sql_comments If enabled, the Hibernate generate comments inside the SQL. It is
used to make debugging easier.
23
Hibernate Cache Properties
Property Description
hibernate.cache.region_prefix It specifies the prefix which is used for second-level cache region
names.
hibernate.cache.use_structured_entries It facilitates Hibernate to store data in the second-level cache in a
more human-friendly format.
24
Properties of Hibernate Configuration
◆ Hibernate Transaction Properties
Property Description
25
Properties of Hibernate Configuration
◆ Other Hibernate Properties
Property Description
hibernate.connection.provider_cl It represents the classname of a custom ConnectionProvider which provides
ass JDBC connections to Hibernate.
hibernate.connection.isolation It is used to set the JDBC transaction isolation level.
26
Annotations in Hibernate
Commonly Used Annotations
@Entity: Marks a class as a persistent entity, indicating that it represents
data stored in a database table.
@Table: Specifies the name of the database table to which the entity is
mapped.
@Id: Identifies the primary key property of the entity.
@GeneratedValue: Configures the strategy for generating identifier values
(e.g., AUTO, SEQUENCE, IDENTITY).
@Column: Provides details about the mapping of a property to a database column, s
uch as the column name, data type, and nullability.
28
Commonly Used Annotations
@Basic: Marks a property as a basic type (e.g., String, int, Date).
@Transient: Excludes a property from persistence.
@Embedded: Map embeddable components as value types.
@Temporal: Specifies the temporal precision of a date/time property.
@Enumerated: Configures the mapping of an enum type.
@Lob: Marks a property as a large object (BLOB or CLOB).
@Version: Enables optimistic locking with a version property.
◆ @CreationTimestamp, @UpdateTimestamp: Automatically set timestamps for
creation and update events.
29
Relationships Annotations in Hibernate
@ManyToOne: This annotation defines a many-to-one relationship between
two entities.
@OneToMany: This annotation defines a one-to-many relationship between
two entities.
@OneToOne: This annotation defines a one-to-one relationship between two
entities.
@ManyToMany: This annotation defines a many-to-many relationship between
two entities.
30
Hibernate Query Language (HQL)
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.
31
Advantage of HQL
◆ Database independent
◆ Supports polymorphic queries
◆ Easy to learn for Java Programmer
32
Query Interface
33
Query Interface
◆ public Query setMaxResult(int rowno) specifies the no. of records to be
retrieved from the relation (table).
◆ public Query setParameter(int position, Object value) it sets the value to
the JDBC style query parameter.
◆ public Query setParameter(String name, Object value) it sets the value to
a named query parameter.
34
Example of HQL paging
◆ Query query=session.createQuery("from Student");
◆ query.setFirstResult(5);
◆ query.setMaxResult(10);
◆ List list=query.list();//will return the records from 5 to 10th number
35
Example of HQL update query
1. Transaction tx=session.beginTransaction();
2. Query q=session.createQuery("update Student set lastName=:n where id=:i");
3. q.setParameter("n",“Sang");
4. q.setParameter("i",1);
5. int status=q.executeUpdate();
6. System.out.println(status);
7. tx.commit();
36
Demo Hibernate
(One To Many)
1. Open Eclipse, File | New | Maven Project
38
2. Check Create a simple project -> Browse Project -> Next
39
3. Fill the information Project -> Click Finish
40
4. Structure of Maven Project
41
5. Create hibernate.cfg.xml
42
6. Create Books in Pojo
43
7. Create Students in Pojo
44
8. Create StudentDAO
45
9. Save Student in StudentDAO
46
10. Get All Student in StudentDAO
47
11. Delete Student in StudentDAO
48
12. Find A Student in StudentDAO
49
13. Update a Student in StudentDAO
50
14. Create IStudentRepository
51
15. Create StudentRepository
52
16. Create IStudentService
53
17. Create StudentService
54
18. Create Main function
55
19. Result
56
20. Result
57
Demo JPA
(Many To Many)
1. Create Books in Pojo’s Package
59
2. Create Students in Pojo’s Package
60
3. Run Program
61
4. Result
62
5. Result
63
Summary
Concepts were introduced:
Overview about Hibernate
Architecture Overview new features of Hibernate
Explain and demo using Eclipse IDE to create Hibernate Console
Create and Run cross-platform Console application with Java connect to
MSSQL with Repository Pattern
64