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

Spring & Hibernate

The document discusses Object-Relational Mapping (ORM) frameworks Spring and Hibernate. It explains that Spring is a popular Java EE framework and Hibernate is a commonly used ORM framework, so they are often used together. It provides overviews of ORM, Hibernate architecture and components, Hibernate annotations, queries and advantages. It also discusses how Spring can enhance Hibernate by simplifying configuration, transaction management and integration with other frameworks and standards.

Uploaded by

20i237
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Spring & Hibernate

The document discusses Object-Relational Mapping (ORM) frameworks Spring and Hibernate. It explains that Spring is a popular Java EE framework and Hibernate is a commonly used ORM framework, so they are often used together. It provides overviews of ORM, Hibernate architecture and components, Hibernate annotations, queries and advantages. It also discusses how Spring can enhance Hibernate by simplifying configuration, transaction management and integration with other frameworks and standards.

Uploaded by

20i237
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Spring & Hibernate -

Object-Relational Mapping

Chapter 4
Spring & Hibernate

● Spring is one of the most used Java EE (Enterprise Edition)


Framework and Hibernate is the most popular ORM(Object
Relational Mapping) framework.
● That’s why Spring Hibernate combination is used a lot in enterprise
applications.
ORM

● Object Relational Mapping (ORM) is a technique used in creating a "bridge"


between object-oriented programs and, in most cases, relational
databases.

● Put another way, you can see the ORM as the layer that connects object oriented
programming (OOP) to relational databases.

● When interacting with a database using OOP languages, you'll have to perform
different operations like creating, reading, updating, and deleting (CRUD) data
from a database. ORM tools help simplify these operations.
ORM

● An example of SQL code that retrieves information about a particular user from a
database:

"SELECT id, name, email, country, phone_number FROM users


WHERE id = 20"

● The code above returns information about a user — name, email, country, and
phone_number — from a table called users. Using the WHERE clause, we
specified that the information should be from a user with an id of 20.

● On the other hand, an ORM tool can do the same query as above with simpler
methods. That is:

users.GetById(20)
Spring Framework
Spring Bean Scopes

● singleton – only one instance of the spring bean will be created for the spring container. This
is the default spring bean scope. While using this scope, make sure bean doesn’t have shared
instance variables otherwise it might lead to data inconsistency issues.

● prototype – A new instance will be created every time the bean is requested from the spring
container.
● request – This is same as prototype scope, however it’s meant to be used for web applications.
A new instance of the bean will be created for each HTTP request.
● session – A new bean will be created for each HTTP session by the container.
● global-session – This is used to create global session beans for Portlet applications.

https://www.journaldev.com/21039/spring-bean-scopes
Hibernate

● Hibernate is an open source project whose purpose is to make it easy to integrate


relational data into Java programs. Hibernate is an Object-Relational Mapping
(ORM) solution for JAVA

● This is done through the use of XML mapping files/annotations, which associate Java
classes with database tables.

● Hibernate provides basic mapping capabilities. It also includes several other


object/relational mapping (ORM) capabilities, including:

i) An enhanced, object-based SQL variant for retrieving data, known as Hibernate Query
Language (HQL).
Hibernate

ii) Automated processes to synchronize objects with their database equivalents. − Built-in
database connection pooling, including three open source variants.

iii) Transactional capabilities that can work both stand-alone or with existing Java Transaction
API (JTA) implementations.

● The goal of Hibernate is to allow object-oriented developers to incorporate persistence into


their programs with a minimum of effort.

● Hibernate takes care of mapping Java classes to database tables using XML files and
without writing any line of code. Provides simple APIs for storing and retrieving Java
objects directly to and from the database. If there is change in the database or in any table,
then you need to change the XML file properties only.
Hibernate Architecture
Hibernate Architecture
Hibernate Architecture

Configuration Object -

● Database Connection − This is handled through one or more configuration files


(hibernate.cfg.xml) supported by Hibernate.

● Class Mapping Setup − This component creates the connection between the Java classes and
database tables.

SessionFactory Object -

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

● If you are using multiple databases, then you would have to create multiple SessionFactory
objects.
Hibernate Architecture

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.

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

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. HQL is suitable for executing Static Queries.

Criteria Object

Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.
Criteria is suitable for executing Dynamic Queries
Supporting Databases

Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines
supported by Hibernate −
● HSQL Database Engine
● DB2/NT
● MySQL
● PostgreSQL
● FrontBase
● Oracle
● Microsoft SQL Server Database
● Sybase SQL Server
● Informix Dynamic Server
Supported Technologies

Hibernate supports a variety of other technologies, including −

● XDoclet Spring
● J2EE
● Eclipse plug-ins
● Maven
Hibernate - Annotations

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

● If you going to make your application portable to other EJB 3 compliant ORM
applications, you must use annotations to represent the mapping information, but still if
you want greater flexibility, then you should go with XML-based mappings.
Hibernate - Annotations

● @Entity annotation defines that a class can be mapped to a table

● @Table annotation allows to specify the details of the table that will be used to persist the entity
in the database.

● @Id: This annotation specifies the primary key of the entity.

● @GeneratedValue: This annotation is used to specify the primary key generation strategy to use

● The @Column annotation is used to specify the details of the column to which a field or property
will be mapped.
Hibernate - Query Language

● Hibernate Query Language (HQL) is an object-oriented query language, similar to


SQL, but instead of operating on tables and columns, HQL works with
persistent objects and their properties.

● HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.

● Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but
properties like table and column names are case sensitive in HQL.
Advantages

● Open Source and Lightweight. Hibernate framework is open source under the LGPL license and
lightweight.

● Fast Performance.

● Database Independent Query.

● Automatic Table Creation.

● Simplifies Complex Join.

● Provides Query Statistics and Database Status.


Spring and Hibernate

Despite their conflicting seasonal allusions, these two frameworks can cooperate neatly within the persistence tier.

● Hibernate can handle persistence more or less by itself.

− It offers object/relational mapping.

− It can manage sessions and transactions.

● Spring brings a few nice features not found in Hibernate:

− The IoC container makes configuring data sources, transaction managers, and DAOs easy.

− It manages the Hibernate SessionFactory as a singleton

– a small but surprisingly annoying task that must be implemented manually when using Hibernate alone.

− It offers a transaction system of its own, which is aspect oriented and thus configurable, either through Spring
AOP or Java-5 annotations. Either of these are generally much easier than working with Hibernate’s transaction
API.
Spring and Hibernate

● As good as Hibernate is, Spring makes it a bit better.

− Transaction management becomes nearly invisible for many applications, and where it’s visible, it’s
still pretty easy.

− You integrate more easily with other standards and frameworks.


Hibernate Example (Annotations)

i) Install MySQL (or any database) service

ii) Create a database & table


Hibernate Example

iii) Mapping of Student class with annotations with the defined Student table.

Create a java project and add the required dependencies


Hibernate Example

iv) Create Application Class


Hibernate Example
Adding a record using hibernate
Hibernate Example

iv) Create hibernate.cfg.xml configuration file to define database related


parameters.
hibernate.cfg.xml
Hibernate.cfg.xml (contd…)
Listing all the students (in Application.java file)
Listing all the students
Listing all the students
Updating Values
Updating Values
Delete Operation

You might also like