0% found this document useful (0 votes)
7 views57 pages

Hibernate Lecture 1

The document provides an overview of Hibernate, a Java framework that simplifies database interactions through Object-Relational Mapping (ORM) and implements the Java Persistence API (JPA). It discusses the advantages of using Hibernate over JDBC, including automatic table creation, database-independent queries, and simplified complex joins. Additionally, it covers Hibernate's architecture, configuration, session management, and the use of annotations for mapping Java classes to database tables.
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)
7 views57 pages

Hibernate Lecture 1

The document provides an overview of Hibernate, a Java framework that simplifies database interactions through Object-Relational Mapping (ORM) and implements the Java Persistence API (JPA). It discusses the advantages of using Hibernate over JDBC, including automatic table creation, database-independent queries, and simplified complex joins. Additionally, it covers Hibernate's architecture, configuration, session management, and the use of annotations for mapping Java classes to database tables.
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/ 57

By

Sudha Agarwal
INDEX
❖ Hibernate Introduction
hibernate
Hibernate is a Java framework that simplifies the development
of Java application to interact with the database.

It is an open source, lightweight, ORM (Object Relational


Mapping) tool.
hibernate
Hibernate implements the specifications of JPA
(Java Persistence API) for data persistence.
Hibernate Vs. JPA

It is not an implementation. It is
Hibernate is an implementation of
only a Java specification.
JPA.
It is a set of rules and guidelines
It helps in mapping Java data
to set interfaces for implementing
types to SQL data types.
object-relational mapping.
hibernate
Hibernate not only takes care of the mapping from Java classes to
database tables (and from Java data types to SQL data types), but
also provides data query and retrieval facilities.
Hibernate Features
Hibernate Features
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.
What Is JDBC?
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.
What Is JDBC?
What Is JDBC?
JDBC Architecture
Pros and Cons of JDBC
❖Pros of JDBC
❖Clean and simple SQL processing
❖Good performance with large data
❖Very good for small applications
❖Simple syntax so easy to learn

❖Cons of JDBC
• Complex if it is used in large projects
• Large programming overhead
• No encapsulation
• Hard to implement MVC concept
• Query is DBMS specific
TO be pasted
TO be changed
Why 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.

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
Why orm?
Granularity

Inheritance

Identity

Associations

Navigation
Why ORM?
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 −

❖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.
ORM Tool
ORM Tool
❖An ORM tool 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.
What is JPA?
❖Java Persistence API (JPA) is a Java specification that provides
certain functionality and standard to ORM tools. The
javax.persistence package contains the JPA classes and interfaces.
What is JPA?
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
Java ORM Frameworks
Advantages of Hibernate
❖1) Open Source and Lightweight
❖Hibernate framework is open source under the LGPL license and
lightweight.

❖2) Fast Performance


❖The performance of hibernate framework is fast because cache is
internally used in hibernate framework. There are two types of cache
in hibernate framework first level cache and second level cache.
First level cache is enabled by default.

❖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.
Advantages of Hibernate
❖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


❖Fetching 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.
Hibernate - Architecture
❖Hibernate has a layered architecture which helps the user to operate
without having to know the underlying APIs. Hibernate makes use of
the database and configuration data to provide persistence services
(and persistent objects) to the application.
Hibernate - 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.
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.
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.
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.
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.
Hibernate Configuration
❖Hibernate requires to know in advance — where to find the mapping
information that defines how your Java classes relate to the database
tables.

❖Hibernate also requires a set of configuration settings related to


database and other related parameters.

❖All such information is usually supplied as a standard Java properties


file called hibernate.properties, or as an XML file named
hibernate.cfg.xml.
Hibernate Properties
❖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.pool_size : Limits the number of connections


waiting in the Hibernate database connection pool.

❖hibernate.connection.autocommit : Allows autocommit mode to be


used for the JDBC connection.
Hibernate with MySQL
❖Create hibernate.cfg.xml configuration file and place it in the root of
your application's classpath.
Hibernate with MySQL
Hibernate Sessions
❖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.

❖The main function of the Session is to offer, create, read, and delete
operations for instances of mapped entity classes.
Hibernate Sessions
❖Instances may exist in one of the following three states at a given
point in time −

❖transient − A new instance of a persistent class, which is not


associated with a Session and has no representation in the database
and no identifier value is considered transient by Hibernate.

❖persistent − You can make a transient instance persistent by


associating it with a Session. A persistent instance has a
representation in the database, an identifier value and is associated
with a Session.

❖detached − Once we close the Hibernate Session, the persistent


instance will become a detached instance.
Hibernate Sessions
❖A Session instance is serializable if its persistent classes are
serializable. A typical transaction should use the following
Persistent Class
❖The entire concept of Hibernate is to take the values from Java class
attributes and persist them to a database table.

❖A mapping document helps Hibernate in determining how to pull the


values from the classes and map them with table and associated
fields.

❖Java classes whose objects or instances will be stored in database


tables are called persistent classes in Hibernate.

❖Hibernate works best if these classes follow some simple rules, also
known as the Plain Old Java Object (POJO) programming model.
Mapping Files
❖An Object/relational mappings are usually defined in an XML
document. This mapping file instructs Hibernate — how to map the
defined class or classes to the database tables?
Mapping Files
❖we can define following mapping file, which instructs Hibernate how to
map the defined class or classes to the database tables.
Mapping Files
❖You should save the mapping document in a file with the format
<classname>.hbm.xml like Employee.hbm.xml.

❖The mapping document is an XML document having


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

❖The <class> elements are used to define specific mappings from a


Java classes to the database tables. The Java class name is specified
using the name attribute of the class element and the database table
name is specified using the table attribute.

❖The <meta> element is optional element and can be used to create


the class description.
Mapping Files
❖The <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, this mapping types will convert from Java to SQL data
type.

❖The <generator> element within the id element is used to generate


the primary key values automatically.

❖The <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
the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to
SQL data type.
Mapping Types
❖When you prepare a Hibernate mapping document, you find that you
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.
Mapping Types
O/R Mappings
❖These are 3 types of mapping:

❖Mapping of collections,
❖Mapping of associations between entity classes, and
❖Component Mappings.
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.
Hibernate - Annotations
❖You have seen how Hibernate uses XML mapping file for the
transformation of data from POJO to database tables and vice versa.
Hibernate annotations are the newest way to define mappings without
the use of XML file.

❖You can 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.
@Entity Annotation
❖The EJB 3 standard annotations are contained in the
javax.persistence package, so we import this package as the first
step.

❖Second, we used the @Entity annotation to the Employee class,


which marks this class as an entity bean, so it must have a
no-argument constructor that is visible with at least protected scope.
@Table Annotation
❖The @Table annotation allows you to specify the details of the table
that will be used to persist the entity in the database.

❖The @Table 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. For now, we are
using just table name, which is EMPLOYEE.
@Id and @GeneratedValue
Annotations
❖Each entity bean will have a primary key, which you annotate on the
class with the @Id annotation. The primary key can be a single field or
a combination of multiple fields depending on your table structure.

❖By default, the @Id annotation will automatically determine the most
appropriate primary key generation strategy to be used but you can
override this by applying the @GeneratedValue annotation, which
takes two parameters strategy and generator.
@Column Annotation
❖The @Column annotation is used to specify the details of the column
to which a field or property will be mapped. You can use column
annotation with the following most commonly used attributes −

❖name attribute permits the name of the column to be explicitly


specified.

❖length attribute permits the size of the column used to map a value
particularly for a String value.

❖nullable attribute permits the column to be marked NOT NULL when


the schema is generated.

❖unique attribute permits the column to be marked as containing only


unique values.

You might also like