You are on page 1of 16

Introduction to SPRING MVC Framework:

A Spring MVC is a Java framework which is used to build web applications. It follows the
Model-View-Controller design pattern. It implements all the basic features of a core spring
framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views.

o Model - A model contains the data of the application. A data can be a single object or
a collection of objects.
o Controller - A controller contains the business logic of an application. Here, the
@Controller annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format. Generally,
JSP+JSTL is used to create a view page. Although spring also supports other view
technologies such as Apache Velocity, Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the front
controller. It is responsible to manage the flow of the Spring MVC application.
Hibernate Framework:
Hibernate is an open-source, object-relational mapping (ORM) framework for
Java applications. It simplifies database access and persistence by providing a
high-level, object-oriented API for interacting with relational databases.
Hibernate abstracts the complexities of SQL queries and database
management, allowing developers to work with Java objects rather than
dealing directly with database tables and SQL statements.
Here are some key aspects of Hibernate and an introduction to its features:
Object-Relational Mapping (ORM): Hibernate is primarily used as an ORM
framework. ORM is a programming technique that maps database tables and
their relationships to Java objects and their associations. This allows developers
to interact with databases using Java objects, making database operations
more natural and less error-prone.
Cross-Database Portability: Hibernate provides a level of database
independence. It abstracts database-specific SQL dialects, so you can write
database-agnostic code. Hibernate can generate SQL statements compatible
with various relational database management systems (RDBMS), such as
MySQL, PostgreSQL, Oracle, and more.
Automatic Table Generation: Hibernate can automatically generate database
tables and schema based on the Java object model. This feature, known as
schema generation or schema evolution, simplifies the database setup process.
Declarative Mapping: Hibernate uses XML or annotations to declare the
mapping between Java objects (entities) and database tables. This mapping is
defined in configuration files or directly in the entity classes using annotations.
Developers can specify relationships, constraints, and other mapping details
declaratively.
Lazy Loading and Caching: Hibernate supports lazy loading of related objects,
which can improve performance by loading data only when needed. It also
provides caching mechanisms to store and retrieve frequently accessed data
from memory, reducing the number of database queries and improving
application performance.
Query Language: Hibernate Query Language (HQL) is a powerful and database-
agnostic query language that resembles SQL but operates on Java objects
rather than database tables. HQL allows developers to write queries in a more
object-oriented way.
Criteria API: Hibernate offers a Criteria API that allows you to construct queries
using a type-safe and object-oriented approach, eliminating the need to write
explicit HQL or SQL queries.
Transaction Management: Hibernate integrates seamlessly with Java EE and
Spring for transaction management. It supports ACID (Atomicity, Consistency,
Isolation, Durability) properties of transactions.
Integration with Other Technologies: Hibernate can be used in conjunction
with various Java technologies and frameworks, including Spring, JavaServer
Faces (JSF), and Java Persistence API (JPA).
Community and Ecosystem: Hibernate has a large and active community of
developers and users. It is a part of the larger Hibernate ecosystem, which
includes related projects like Hibernate Validator (for data validation) and
Hibernate Search (for full-text searching).
Open Source: Hibernate is open-source software released under the GNU
Lesser General Public License (LGPL). This means it's free to use, modify, and
distribute.
--------------------------------------------------------------------------------------------------------------------------------------
Hibernate Architecture:
Hibernate has a layered architecture that allows users to operate without being
aware of the core APIs.
Hibernate makes use of databases and other configurable information to
provide unique features.
Hibernate’s architecture is divided into four major levels:
Hibernate framework.
Backhand API.
Java application layer.
Database level.
Hibernate’s architecture is shown in the following diagram:

The diagram below highlights Hibernate’s core classes:


Architecture components:

Application-level class objects are summarized in this section:

• SessionFactory object: SessionFactory is a session and client factory for


the ConnectionProvider. It saves data in the second-level cache.
• Session object: The session object serves as a link between the database
and the application’s data layer. It is a tiny object that wraps the JDBC
connection. It acts as a factory for transactions, queries, as well as other
criteria.
• Transaction object: The transaction interface provides different
functions or methods required for data management.
• ConnectionProvider: It’s a factory for JDBC connections. In other words,
it hides the application’s connection to the data source.
• TransactionFactory: This is an optional factory that is used for different
transactions.

--------------------------------------------------------------------------------------------
Configuration of Hibernate Framework:

The basic steps for downloading and installing Hibernate in the Eclipse IDE are
as follows:

Step 1: Select Help » Eclipse Marketplace from the Eclipse IDE’s menu bar.

Step 2: Type JBoss Tool on the search box and click on Go.

Step 3: Choose the latest version of JBoss Tools and click Install.
Step 4: From the marked tools, select and download the Hibernate tool.
Then click on confirm to set up the hibernate tools.
Step 5: Accept the terms in the license agreement and click on
the Finish button.

Step 6: Restart Eclipse IDE to ensure that all changes are reflected.

Step 7: To validate whether the Hibernate tools are correctly installed, click
on File » New » Others and then search for Hibernate.

---------------------------------------------------------------------------------------------------------

HIBERANATE O/R (Object Relational) Mapping:


ORM is a programming technique that allows developers to interact with
relational databases using Java objects. Hibernate simplifies database access by
abstracting away the complexities of SQL and providing a high-level, object-
oriented API for data persistence.
Here's how Hibernate's Object-Relational Mapping works:
Mapping Java Objects to Database Tables:
In Hibernate, Java objects are mapped to database tables. Each Java class that
you want to persist in the database is referred to as an entity. The entity's
attributes are mapped to columns in the corresponding database table. This
mapping is typically defined using annotations or XML configuration files.
For example, consider a User Java class:

In this example, the User class is annotated with @Entity, indicating that it is a
JPA entity. The @Table annotation specifies the database table name, and @Id
marks the primary key field.

Session Factory:
Hibernate uses a SessionFactory to manage the persistence of entities. The
SessionFactory is a heavyweight object that is typically created once per
application and serves as a factory for creating Session objects.

SessionFactory sessionFactory = new


Configuration().configure().buildSessionFactory();
The configure() method loads Hibernate configuration settings, which can be
specified in a hibernate.cfg.xml file.
Session:
A Session in Hibernate is a short-lived, lightweight object that represents a
single unit of work with the database. Developers use Session objects to
perform CRUD (Create, Read, Update, Delete) operations on entities. Sessions
are typically created and managed within a specific scope, such as a web
request or a transaction.
Session session = sessionFactory.openSession();
Transactions:
Hibernate encourages the use of transactions for database operations.
Transactions ensure that changes to the database are consistent and atomic.
You can manage transactions using the Transaction API provided by Hibernate.

Transaction transaction = session.beginTransaction();


// Perform database operations here
transaction.commit(); // Commit the transaction
CRUD Operations:
Hibernate provides methods for performing CRUD operations on entities. For
example:
session.save(entity): Persist a new entity in the database.
session.get(User.class, id): Retrieve an entity by its primary key.
session.update(entity): Update an existing entity.
session.delete(entity): Delete an entity.
session.createQuery("FROM User").list(): Execute HQL queries to retrieve
entities.
Lazy Loading and Eager Fetching:
Hibernate supports lazy loading, which means related entities are loaded from
the database only when they are accessed. This can improve performance by
minimizing the amount of data fetched from the database. Developers can
configure fetching strategies as needed.
Caching:
Hibernate includes caching mechanisms to improve performance by storing
frequently accessed data in memory. This reduces the need for repeated
database queries.
Query Language:
Hibernate Query Language (HQL) allows developers to write database queries
using an object-oriented syntax that is similar to SQL but operates on Java
objects rather than database tables.
Integration with Spring and Java EE:
Hibernate can be seamlessly integrated with Spring and Java EE for transaction
management, dependency injection, and other enterprise features.

---------------------------------------------------------------------------------------------------------

Implementing Hibernate O/R Mappings:


Here's a step-by-step guide on how to implement Hibernate ORM in a Java
project:
Set Up Your Project:
Start by creating a Java project using your preferred development environment
(e.g., Eclipse, IntelliJ IDEA, or a build tool like Maven or Gradle). Make sure to
include the necessary dependencies for Hibernate in your project's build file.
For example, if you're using Maven, add the Hibernate dependencies to your
pom.xml:

Define Entity Classes:


Create Java classes that represent your database tables. These classes are
referred to as entities and should be annotated with @Entity. Define fields and
annotate them to map to specific database columns.
<!--hibernate.cfg.xml -->
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</pro
perty>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/myd
b</property>
<property
name="hibernate.connection.username">username</property>
<property
name="hibernate.connection.password">password</property>
<!-- Specify entity classes here -->
<mapping class="com.example.User"/>
</session-factory>
</hibernate-configuration>
Initialize Hibernate SessionFactory:
In your application, create a SessionFactory object based on the Hibernate
configuration. You typically do this at the application startup.

Configuration configuration = new


Configuration().configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Perform Database Operations:
You can now use Hibernate to perform CRUD operations on your entities. For
example, to save a new user:

Hibernate will generate the appropriate SQL statements to insert the new user
into the database.
Querying with Hibernate:
Hibernate provides various ways to query data, including using Hibernate
Query Language (HQL), Criteria API, or native SQL queries.
Example HQL query to retrieve users:
Hibernate provides various ways to query data, including using Hibernate
Query Language (HQL), Criteria API, or native SQL queries.
Example HQL query to retrieve users:

Handle Transactions:
It's essential to manage transactions properly when using Hibernate. Begin a
transaction before performing database operations and commit or roll back the
transaction as needed.
Close Resources:
Always close Hibernate resources like sessions and session factories when
you're done using them to free up database connections and prevent resource
leaks.
Testing:
Test your Hibernate-based data access layer with unit tests to ensure it
functions correctly.
Logging and Error Handling:
Configure appropriate logging to help diagnose issues and handle exceptions
gracefully.
Integration:
Integrate Hibernate into your application, whether it's a standalone Java
application, a Java EE application, or a Spring Boot application, depending on
your project's requirements.
---------------------------------------------------------------------------------------------------------

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.

FROM Clause

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 −

String hql = "FROM Employee";


Query query = session.createQuery(hql);
List results = query.list();

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

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 −

String hql = "FROM Employee AS E";


Query query = session.createQuery(hql);
List results = query.list();

The AS keyword is optional and you can also specify the alias directly after the
class name, as follows −

String hql = "FROM Employee E";


Query query = session.createQuery(hql);
List results = query.list();
SELECT Clause

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 −

String hql = "SELECT E.firstName FROM Employee E";


Query query = session.createQuery(hql);
List results = query.list();

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


rather than a field of the EMPLOYEE table.

WHERE Clause

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 −

String hql = "FROM Employee E WHERE E.id = 10";


Query query = session.createQuery(hql);
List results = query.list();
ORDER BY Clause

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 −

String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

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 −

String hql = "FROM Employee E WHERE E.id > 10 " +


"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();
GROUP BY Clause

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 −

String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +


"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();
Using Named Parameters

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 −

String hql = "FROM Employee E WHERE E.id = :employee_id";


Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();
UPDATE Clause

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.

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 −

String hql = "UPDATE Employee set salary = :salary " +


"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
DELETE Clause

The DELETE clause can be used to delete one or more objects. Following is the
simple syntax of using DELETE clause −

String hql = "DELETE FROM Employee " +


"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
INSERT Clause

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 −

String hql = "INSERT INTO Employee(firstName, lastName, salary)" +


"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

You might also like