Spring MVC-Hibernate
Spring MVC-Hibernate
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:
--------------------------------------------------------------------------------------------
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.
---------------------------------------------------------------------------------------------------------
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.
---------------------------------------------------------------------------------------------------------
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.
---------------------------------------------------------------------------------------------------------
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 −
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 −
The AS keyword is optional and you can also specify the alias directly after the
class name, as follows −
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 −
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 −
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 −
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 −
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 −
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 −
The DELETE clause can be used to delete one or more objects. Following is the
simple syntax of using DELETE 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 −