0% found this document useful (0 votes)
1 views24 pages

Finall Java

Uploaded by

mondalshreejit66
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)
1 views24 pages

Finall Java

Uploaded by

mondalshreejit66
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

UNIT 1 : JAVA EE

1. Java SE (Java Standard Edition)


Java SE (Standard Edition) is the core version of Java used for developing standalone and desktop
applications. It provides the basic features of Java such as object-oriented programming, exception
handling, multithreading, collections, input-output streams, and networking. Java SE forms the
foundation of all Java technologies and is mainly used to develop desktop applications and console-
based programs.
Features of Java SE:
• Platform independent.
• Object-oriented.
• Supports multithreading.
• Robust and secure.
• Provides APIs for networking and I/O.
Applications:
• Desktop applications.
• Console applications.
• Scientific applications.
• Basic software development.

2. Java EE (Java Enterprise Edition)


Java EE (Enterprise Edition) is an extension of Java SE used for developing web-based and enterprise-
level applications. It provides additional technologies such as JSP, Servlet, JDBC, Hibernate, EJB, and
Web Services for building distributed and dynamic web applications.
Java EE is mainly used in large-scale business applications that require security, transaction
management, database connectivity, and web services.
Components of Java EE:
• Servlet
• JSP
• JDBC
• Hibernate
• EJB
• Web Services
Applications:
• E-commerce websites.
• Banking applications.
• Enterprise applications.
• Web applications.
• Online management systems.

3. Difference between Java SE and Java EE


Java SE Java EE
Standard Edition Enterprise Edition
Used for desktop applications Used for web applications
Provides basic Java APIs Provides enterprise APIs
Supports standalone applications Supports distributed applications
Does not support Servlet and JSP Supports Servlet and JSP
Small-scale applications Large-scale applications
Limited database support Extensive database support
Used for core Java programming Used for enterprise programming
Advantages of Java EE
1. Platform independent.
2. Supports web applications.
3. Provides database connectivity.
4. Supports transaction management.
5. Highly secure.
6. Scalable and reliable.
7. Supports distributed applications.

Disadvantages of Java EE
1. More complex than Java SE.
2. Requires application servers.
3. Higher memory consumption.
4. Difficult to learn for beginners.
5. Development cost is high.

UNIT 2 : JDBC (Java Database Connectivity)


1. JDBC Introduction
JDBC (Java Database Connectivity) is a standard Java API used to establish a connection between
Java applications and databases. It allows Java programs to perform database operations such as
inserting, updating, deleting, and retrieving data. JDBC acts as a bridge between the Java application
and the database management system.
JDBC provides various classes and interfaces that help programmers execute SQL statements and
process the results. It is platform-independent and supports different databases such as Oracle,
MySQL, SQL Server, and PostgreSQL.
Features of JDBC:
• Database connectivity.
• Executes SQL queries.
• Platform independent.
• Supports transactions.
• Provides security.
Advantages:
• Easy database access.
• Supports multiple databases.
• High portability.
• Efficient data handling.
2. JDBC Architecture
JDBC (Java Database Connectivity) Architecture describes the interaction between a Java application
and a database. It acts as a bridge that enables Java programs to communicate with different
database systems. JDBC provides a standard API that allows programmers to execute SQL queries,
retrieve data, and perform database operations.
The JDBC architecture consists of several components that work together to establish
communication between the Java application and the database.
JDBC Architecture Diagram
Java Application

JDBC API

DriverManager

JDBC Driver ----> Database
Components of JDBC Architecture
1. Java Application
It is the user program developed using Java. The application sends requests to the database and
receives the results.
Functions:
• Sends SQL queries.
• Receives data.
• Performs business logic.

2. JDBC API
JDBC API consists of classes and interfaces provided by Java for database programming. It acts as an
interface between the application and the JDBC driver.
Important interfaces:
• Connection
• Statement
• PreparedStatement
• ResultSet
• CallableStatement

3. DriverManager
DriverManager is a class that manages all database drivers. It establishes a connection between the
Java application and the database. Functions:
• Loads drivers.
• Establishes connections.
• Manages multiple drivers.
Example: Connection con =
[Link](url,user,password);

4. JDBC Driver
A JDBC driver is software that converts Java method calls into database-specific commands.
Functions:
• Communicates with the database.
• Executes SQL commands.
• Returns results to Java.

5. Database
The database stores and manages data. JDBC supports various databases such as:
• Oracle
• MySQL
• SQL Server
• PostgreSQL
The database receives SQL commands and sends the result back to the Java application.

Working of JDBC Architecture


1. The Java application sends a request.
2. JDBC API receives the request.
3. DriverManager loads the appropriate driver.
4. The JDBC driver communicates with the database.
5. The database executes the SQL query.
Advantages of JDBC Architecture
1. Platform independent.
2. Database independent.
3. Supports multiple databases.
4. Easy connectivity.
5. Efficient data processing.
6. Provides security.
7. Supports transaction management.

Disadvantages of JDBC Architecture


1. Requires more coding.
2. Manual SQL writing.
3. Database-specific drivers are needed.
4. Difficult to maintain large applications.

Conclusion
JDBC Architecture provides a standard mechanism for communication between Java applications
and databases. It consists of the Java Application, JDBC API, DriverManager, JDBC Driver, and
Database. This architecture makes database operations simple, secure, and efficient.

3. JDBC Drivers
A JDBC Driver is a software component that enables communication between a Java application and
a database. It converts JDBC API calls into database-specific commands that the database can
understand. Without a JDBC driver, a Java application cannot establish a connection with the
database.
The JDBC driver acts as a translator between the Java program and the database management
system. Different databases require different JDBC drivers.
Functions of JDBC Driver:
• Establishes database connection.
• Converts Java commands into SQL commands.
• Executes SQL queries.
• Returns results to the application.
• Provides communication between Java and the database.
Advantages:
• Easy database connectivity.
• Platform independent.
• Supports multiple databases.
• Efficient communication.

4. Types of JDBC Drivers


There are four types of JDBC drivers.
Type 1: JDBC-ODBC Bridge Driver
This driver converts JDBC calls into ODBC calls.
Advantages:
• Easy to use.
• Suitable for small applications.
Disadvantages:
• Slow performance.
• Requires ODBC installation.
• Platform dependent.

Type 2: Native API Driver


It converts JDBC calls into native database API calls.
Advantages:
• Better performance.
• Database-specific optimization.
Disadvantages:
• Requires native libraries.
• Platform dependent.

Type 3: Network Protocol Driver


It uses middleware to communicate with the database.
Advantages:
• Platform independent.
• Supports multiple databases.
Disadvantages:
• Requires middleware server.
• Slower than Type 4.

Type 4: Thin Driver


It directly communicates with the database using native protocols.
Advantages:
• Fast performance.
• Platform independent.
• No middleware required.
• Most widely used.
Disadvantages:
• Database-specific driver.

Comparison of JDBC Drivers


Type Name Platform Speed
Type 1 JDBC-ODBC Dependent Slow
Type 2 Native API Dependent Moderate
Type 3 Network Protocol Independent Good
Type 4 Thin Driver Independent Fast

5. JDBC Steps
The following six steps are used to establish database connectivity.
Step 1: Import Packages
Import the required JDBC package.
import [Link].*;

Step 2: Load Driver


The appropriate driver is loaded into memory.
[Link]();

Step 3: Establish Connection


Connection between Java and the database is established.
[Link]();

Step 4: Create Statement


Create Statement or PreparedStatement object.

Step 5: Execute Query


Execute SQL queries.
executeQuery();
executeUpdate();

Step 6: Close Connection


Close all resources.
[Link]();

Advantages of JDBC Steps


• Simple process.
• Easy database connectivity.
• Efficient query execution.

6. Statement
Statement is an interface used to execute simple SQL queries.
It executes SQL statements directly without parameters.
Features:
• Executes static SQL queries.
• Simple to use.
• Suitable for small applications.
Advantages:
• Easy implementation.
• Less coding.
Disadvantages:
• Slow execution.
• SQL injection possible.
• Not reusable.
Example:
Statement st=[Link]();

7. PreparedStatement
PreparedStatement is a precompiled SQL statement used to execute parameterized queries.
It improves performance and security.
Features:
• Precompiled query.
• Parameter support.
• Reusable.
Advantages:
• Faster execution.
• Prevents SQL injection.
• More secure.
• Better performance.

Disadvantages:
• Slightly complex.
• Suitable for predefined queries.
Example:PreparedStatement ps=
[Link](
"insert into student values(?,?)");

Difference between Statement and PreparedStatement


Statement PreparedStatement
Static SQL Parameterized SQL
Slow Fast
Not secure Secure
SQL injection possible Prevented
Not reusable Reusable

8. CallableStatement
CallableStatement is used to execute stored procedures in the database.
Stored procedures are precompiled SQL programs stored inside the database.
Advantages:
• Faster execution.
• Reduced network traffic.
• Reusable code.
• Better performance.
Applications:
• Banking systems.
• Payroll systems.
• Enterprise applications.
Example:CallableStatement cs=
[Link]();

Difference between PreparedStatement and CallableStatement


PreparedStatement CallableStatement
Executes SQL query Executes stored procedure
Uses parameters Uses stored procedures
Moderate performance High performance

9. ResultSet
ResultSet is an object used to store the records returned by the database after executing a SELECT
query.
It allows row-by-row processing of data.
Important Methods:
• next()
• getString()
• getInt()
• getDate()
Advantages:
• Easy data retrieval.
• Sequential access.
• Efficient processing.
Example:ResultSet rs=
[Link]();

10. Transaction Management


A transaction is a group of SQL statements executed as a single unit.
Transaction management ensures data consistency and reliability.
A transaction follows ACID properties:
A – Atomicity
All operations execute together.
C – Consistency
Database remains consistent.
I – Isolation
Transactions remain independent.
D – Durability
Changes become permanent.

Advantages:
• Maintains data integrity.
• Prevents data loss.
• Supports recovery.
• Ensures consistency.

11. Commit
The commit() method permanently saves the changes made to the database.
After commit, changes cannot be undone.
Example: [Link]();
Advantages:
• Saves changes permanently.
• Ensures consistency.
• Maintains integrity.

12. Rollback
The rollback() method cancels all changes made during a transaction.
It restores the previous state of the database.
Example:
[Link]();
Advantages:
• Prevents incorrect data.
• Restores previous data.
• Handles errors efficiently.

Difference between Commit and Rollback


Commit Rollback
Saves changes Cancels changes
Permanent action Undo operation
Used after success Used after failure

Conclusion
JDBC provides a standard mechanism for database connectivity in Java. JDBC drivers establish
communication with databases, Statement and PreparedStatement execute SQL queries, ResultSet
retrieves data, and transaction management ensures consistency and reliability.

UNIT 3 : JSP (Java Server Pages)


1. JSP Introduction
Java Server Pages (JSP) is a server-side technology used to develop dynamic web pages. It allows
HTML code and Java code to be embedded together in a single file. JSP pages are executed on the
server, and the generated output is sent to the client in the form of HTML pages.
A JSP file has the extension .jsp. During execution, the JSP page is first translated into a Servlet and
then compiled into a class file by the web container.
JSP is mainly used for the presentation layer of web applications and provides an easier way to
develop user interfaces compared to Servlets.
Features of JSP
• Server-side technology.
• Platform independent.
• Supports dynamic web pages.
• Supports JavaBeans.
• Supports Expression Language and JSTL.
• Easy integration with databases.
Applications of JSP
• Online registration systems.
• Banking applications.
• E-commerce websites.
• Student management systems.
• Enterprise web applications.

2. Advantages of JSP
JSP provides several advantages over traditional Servlets for web application development.
Advantages
1. Easy to write and maintain.
2. Reduces Java coding.
3. Supports reusable components.
4. Provides better separation of presentation and business logic.
5. Supports JavaBeans, EL, and JSTL.
6. Platform independent.
7. Faster web application development.
Disadvantages
1. First request execution is slower.
2. Debugging is difficult.
3. Not suitable for complex business logic.

3. JSP Life Cycle


The JSP Life Cycle describes the various stages through which a JSP page passes from creation to
destruction.
JSP Life Cycle Diagram
JSP Page

Translation

Compilation

Class Loading

Instantiation

jspInit()

_jspService()

jspDestroy()
Stages of JSP Life Cycle
1. Translation
The JSP page is translated into a Servlet source file.
2. Compilation
The generated Servlet file is compiled into a class file.
3. Class Loading
The class file is loaded into memory.
4. Instantiation
An object of the Servlet class is created.
5. jspInit()
This method is called only once to initialize the JSP page.
6. _jspService()
This method processes every client request.
7. jspDestroy()
This method is called once before destroying the JSP page.
Advantages of JSP Life Cycle
• Efficient memory management.
• Better performance after compilation.
• Faster execution for subsequent requests.

4. JSP Directives
JSP Directives provide instructions to the JSP container during the translation phase.
There are three types of directives.
(a) Page Directive
It provides information about the JSP page.
Syntax:<%@ page %>
Functions:
• Specifies language.
• Error handling.
• Imports packages.

(b) Include Directive


It includes another file during translation time.
Syntax:
<%@ include file="[Link]" %>
Advantages:
• Reusability.
• Reduces code duplication.

(c) Taglib Directive


It is used to include custom tag libraries.
Syntax:<%@ taglib uri="" prefix="c" %>
Advantages:
• Supports JSTL.
• Reduces Java code.

5. JSP Scripting Elements


JSP provides scripting elements to insert Java code into HTML pages.
There are three types of scripting elements.

(a) Scriptlet Tag


Scriptlet is used to write Java statements inside JSP.
Syntax:
<% Java statements;%>
Example:<%int a=10;%>

(b) Expression Tag


Expression tag is used to display values directly.
Syntax:<%= expression %>
Example:<%= a %>

(c) Declaration Tag


Declaration tag is used to declare variables and methods.
Syntax:<%! declaration %>
Example:<%! int a=10; %>

Difference between Scripting Elements


Scriptlet Expression Declaration
Executes statements Displays output Declares variables
<% %> <%= %> <%! %>

6. JSP Implicit Objects


JSP provides nine predefined objects known as implicit objects. These objects are automatically
available to the JSP page.
Implicit Object Description
request Contains client request information
response Sends response to client
out Writes output
session Maintains session information
Implicit Object Description
application Represents application context
config Servlet configuration information
page Current JSP object
pageContext Accesses page attributes
exception Handles exceptions
Advantages
• No need to create objects manually.
• Simplifies programming.
• Provides easy access to server resources.

7. Expression Language (EL)


Expression Language (EL) is used to access application data without writing Java code.
It simplifies JSP pages and improves readability.
Syntax
${expression}
Examples
${[Link]}
${[Link]}
${[Link]}
Advantages
1. Reduces Java code.
2. Improves readability.
3. Easy data access.
4. Simplifies web pages.

8. JSTL (Java Standard Tag Library)


JSTL is a collection of custom tags that simplifies JSP programming by reducing the use of Java code.
It provides tags for iteration, conditional statements, database access, and formatting.
Advantages
• Reduces scriptlets.
• Improves readability.
• Easy maintenance.
• Reusable tags.

9. Core Tags
JSTL Core Tags are commonly used tags for control statements and output.
(a) <c:out>
Displays output.
Example: <c:out value="${name}"/>
(b) <c:if>
Used for conditional statements.
Example:<c:if test="${a>10}">

(c) <c:forEach>
Used for looping.
Example:<c:forEach var="i" begin="1" end="5">

(d) <c:choose>
Works like a switch statement.
Example:<c:choose>
Advantages of Core Tags
• Less coding.
• Easy readability.
• Better maintainability.
• Reduces Java code.

10. JavaBeans
JavaBeans are reusable software components written in Java. A JavaBean is a Java class that follows
specific conventions.
Characteristics of JavaBeans
1. Public class.
2. Private instance variables.
3. Getter methods.
4. Setter methods.
5. No-argument constructor.
6. Implements Serializable interface.
Advantages of JavaBeans
• Reusable components.
• Easy maintenance.
• Encapsulation.
• Portability.
• Reduces code duplication.
Role of JavaBeans in MVC
• Model → JavaBean
• View → JSP
• Controller → Servlet

Conclusion
JSP is an important server-side technology used for developing dynamic web applications. Features
such as JSP directives, scripting elements, implicit objects, EL, JSTL, and JavaBeans simplify web
application development and improve code maintainability and reusability.

UNIT 4 : SERVLET
1. Servlet Introduction
Servlet is a server-side Java program used to handle client requests and generate dynamic
responses. It runs inside a web container such as Apache Tomcat and provides a mechanism for
developing web applications.
A Servlet receives requests from the client, processes the request, communicates with the database
if necessary, and sends the response back to the client.
Servlets are mainly used to implement business logic and act as the controller in MVC architecture.
Features of Servlet
• Platform independent.
• Server-side technology.
• Dynamic web page generation.
• High performance.
• Supports session management.
• Provides security.

Advantages of Servlet
1. Better performance than CGI.
2. Platform independent.
3. Supports multithreading.
4. Efficient memory management.
5. Portable and reusable.
6. Secure and robust.
Applications of Servlet
• Online registration systems.
• Banking applications.
• E-commerce websites.
• Student management systems.
• Enterprise web applications.

2. Servlet Life Cycle


The Servlet Life Cycle describes the various stages through which a servlet passes from its creation to
destruction.
Servlet Life Cycle Diagram
Loading

Instantiation

init()

service()

destroy()
Stages of Servlet Life Cycle
1. Loading
The servlet class is loaded by the web container.
2. Instantiation
An object of the servlet class is created.
3. init()
The init() method is called only once to initialize the servlet.
Syntax:
public void init()
4. service()
The service() method processes client requests.
Syntax:
public void service()
5. destroy()
The destroy() method is called before removing the servlet from memory.
Syntax:
public void destroy()
Advantages
• Efficient request processing.
• Better resource management.
• Improved performance.

3. GET and POST Methods


GET and POST are HTTP request methods used to communicate between the client and server.
GET Method
The GET method sends data through the URL.
Advantages
• Faster execution.
• Simple implementation.
• Bookmarking possible.
Disadvantages
• Less secure.
• Limited data size.
• Data visible in URL.

POST Method
The POST method sends data through the request body.
Advantages
• More secure.
• Large amount of data.
• Data not visible.
Disadvantages
• Slower than GET.
• Cannot bookmark.

Difference between GET and POST


GET POST
Data in URL Data in request body
Less secure More secure
Limited size Large size
Faster Slightly slower
Bookmark possible Not possible

4. ServletConfig
ServletConfig is an interface that provides configuration information to a particular servlet.
Each servlet has its own ServletConfig object.
Functions
• Reads initialization parameters.
• Provides configuration details.
• Used by a single servlet.
Methods
• getInitParameter()
• getInitParameterNames()
• getServletContext()
Advantages
• Easy configuration.
• Servlet-specific information.
• Improves flexibility.

5. ServletContext
ServletContext is an interface that provides information about the entire web application.
A single ServletContext object is shared among all servlets.
Functions
• Shares information among servlets.
• Provides application-level data.
• Accesses resources.
Methods
• getAttribute()
• setAttribute()
• removeAttribute()
Advantages
• Global data sharing.
• Resource management.
• Application-wide communication.

Difference between ServletConfig and ServletContext


ServletConfig ServletContext
One servlet Entire application
Private to servlet Shared by all servlets
Servlet-level data Application-level data
Multiple objects Single object

6. Session Management
Session Management is used to maintain the state of a user between multiple requests.
HTTP is a stateless protocol, so session management techniques are required to maintain user
information.
Session Management Techniques
1. Cookies
2. HttpSession
3. URL Rewriting
4. Hidden Form Fields
Advantages
• Maintains user data.
• Provides personalization.
• Improves security.
• Supports user authentication.

7. Cookies
Cookies are small text files stored on the client's computer by the web browser.
They store user information and help maintain sessions.
Features
• Stored on client machine.
• Small amount of data.
• Persistent storage.
Advantages
• Maintains user information.
• Faster access.
• Reduces server load.
Disadvantages
• Less secure.
• Can be deleted.
• Limited storage.

8. HttpSession
HttpSession is an interface used to create and maintain sessions on the server.
It stores user-specific information during a session.
Methods
• setAttribute()
• getAttribute()
• invalidate()
Advantages
• More secure than cookies.
• Server-side storage.
• Easy session management.
Disadvantages
• Increases server memory usage.
• Session timeout may occur.

Difference between Cookie and HttpSession


Cookie HttpSession
Stored on client Stored on server
Less secure More secure
Limited size Larger storage
Can be deleted Controlled by server

9. RequestDispatcher
RequestDispatcher is an interface used to transfer requests from one resource to another.
It helps in request forwarding and resource inclusion.
Methods
forward()
Transfers control to another resource.
include()
Includes the content of another resource.
Advantages
• Reusability.
• Better communication.
• Efficient request handling.

Difference between forward() and include()


forward() include()
Transfers control Includes content
Stops current processing Continues processing
One response Combined response

10. Filters
A Filter is a server-side component used to intercept requests and responses before they reach the
servlet.
Filters perform preprocessing and postprocessing tasks.
Filter Life Cycle
Loading-> init()->doFilter()->destroy()

Methods
init()
Initializes the filter.
doFilter()
Processes the request and response.
destroy()
Removes the filter.
Applications of Filters
• Authentication.
• Logging.
• Data validation.
• Encryption.
• Compression.
Advantages
1. Improves security.
2. Provides centralized processing.
3. Reduces code duplication.
4. Easy request validation.

Conclusion
Servlets are important server-side components used to process client requests and generate
responses. Features such as ServletConfig, ServletContext, Session Management, Cookies,
HttpSession, RequestDispatcher, and Filters make servlet technology efficient and suitable for
developing enterprise web applications.

UNIT 5 : MVC (Model View Controller)


1. MVC Architecture
MVC (Model View Controller) is a software design pattern used for developing web applications. It
divides the application into three components namely Model, View, and Controller. This separation
makes the application easier to develop, maintain, and manage.
In MVC architecture, the user sends a request to the Controller. The Controller processes the
request with the help of the Model and sends the result to the View. The View then displays the
output to the user.
MVC Architecture Diagram
User

Controller (Servlet)

Model (JavaBean)

View (JSP)

User

2. Advantages of MVC
1. Separation of business logic and presentation.
2. Easy maintenance of code.
3. Reusable components.
4. Better scalability.
5. Easy testing and debugging.
6. Multiple developers can work simultaneously.
3. Model
Model is responsible for handling the business logic and database operations of the application. It
stores the application data and processes user requests.
Functions of Model
• Stores data.
• Performs calculations.
• Communicates with the database.
• Implements business logic.
In Java web applications, JavaBeans are generally used as the Model component.

4. View
View is responsible for displaying the output to the user. It represents the presentation layer of the
application.
Functions of View
• Displays data.
• Generates user interface.
• Interacts with the user.
JSP pages are generally used as the View component.

5. Controller
Controller acts as an intermediary between the Model and View. It receives user requests, processes
them, and sends the response to the appropriate View.
Functions of Controller
• Receives client requests.
• Calls Model methods.
• Sends data to View.
• Controls application flow.
Servlets are generally used as the Controller component.

Conclusion
MVC is a design pattern that separates an application into Model, View, and Controller components.
It improves maintainability, scalability, and code reusability, making it suitable for enterprise web
applications.

UNIT 6 : HIBERNATE
1. Hibernate Introduction
Hibernate is an open-source Object Relational Mapping (ORM) framework used for developing
database applications in Java. It simplifies database programming by mapping Java objects to
database tables.
Hibernate eliminates the need for writing large amounts of SQL code and provides automatic table
generation, transaction management, and data retrieval facilities.
Hibernate supports various databases such as Oracle, MySQL, SQL Server, and PostgreSQL.
Features of Hibernate
• Open source framework.
• Supports ORM.
• Database independent.
• Automatic table creation.
• Provides transaction management.
• Supports HQL.
Applications
• Enterprise applications.
• Banking systems.
• E-commerce applications.
• Management systems.

2. ORM (Object Relational Mapping)


ORM is a technique used to map Java objects with database tables. It creates a relationship between
object-oriented programming and relational databases.
In ORM:
Java Database
Class Table
Object Row
Variable Column
ORM reduces the amount of SQL code and makes applications easier to maintain.
Advantages of ORM
1. Reduces coding.
2. Improves maintainability.
3. Provides portability.
4. Reduces database dependency.
5. Increases productivity.

3. Hibernate Architecture
Hibernate Architecture describes how Hibernate communicates with the database.
Application

Configuration

SessionFactory

Session

Transaction

Database
Components
Configuration
Loads Hibernate configuration files.
SessionFactory
Creates Session objects.
Session
Performs database operations.
Transaction
Manages transactions.
Database
Stores application data.
Hibernate architecture provides efficient communication between Java applications and databases.

4. SessionFactory
SessionFactory is an interface in Hibernate responsible for creating Session objects. It is a factory
object that reads the Hibernate configuration file and creates Session objects whenever required.
A SessionFactory object is created only once during the execution of the application because it is a
heavy-weight object and consumes more memory.
SessionFactory is thread-safe and can be shared by multiple users or threads simultaneously.
Functions of SessionFactory
• Creates Session objects.
• Stores mapping information.
• Maintains second-level cache.
• Provides database connectivity.
• Improves application performance.
Characteristics
• Heavy-weight object.
• Created once per application.
• Thread-safe.
• Shared among users.
Advantages
1. Improves performance.
2. Reduces object creation.
3. Provides caching mechanism.
4. Efficient resource utilization.
5. Supports multiple sessions.
Example
SessionFactory sf =
new Configuration()
.configure()
.buildSessionFactory();

5. Session
Session is an interface that acts as a communication link between the Java application and the
database. It provides methods to perform database operations such as insert, update, delete, and
retrieve data.
Session objects are lightweight and short-lived. A Session object is created whenever a database
operation is required and closed after completion.
Functions of Session
• Saves objects.
• Updates objects.
• Deletes objects.
• Retrieves objects.
• Manages transactions.
Important Methods
• save()
• update()
• delete()
• get()
• load()
• close()
Advantages
1. Easy database operations.
2. Reduces SQL coding.
3. Lightweight object.
4. Efficient communication.
5. Supports transactions.
Example
Session session =
[Link]();

Difference between SessionFactory and Session


SessionFactory Session
Creates Session objects Performs database operations
Heavy-weight Light-weight
Thread-safe Not thread-safe
Created once Created many times
Long-lived Short-lived

6. Transaction
Transaction is a group of database operations executed as a single unit. It ensures that either all
operations are completed successfully or none of them are executed.
Transactions help maintain consistency and integrity of the database.
Transaction Process
1. Begin transaction.
2. Perform operations.
3. Commit changes.
4. Rollback if error occurs.
Important Methods
beginTransaction()
commit()
rollback()
Advantages
1. Maintains consistency.
2. Prevents data loss.
3. Ensures reliability.
4. Supports recovery.
5. Maintains integrity.
Example
Transaction tx =
[Link]();
[Link]();

7. CRUD Operations
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations performed
on database records.

Create Operation
The save() method is used to insert data into the database.
[Link](object);

Read Operation
The get() method retrieves data from the database.
[Link]([Link],id);
Update Operation
The update() method modifies existing records.
[Link](object);

Delete Operation
The delete() method removes records from the database.
[Link](object);

Advantages of CRUD Operations


1. Easy data manipulation.
2. Less coding.
3. Efficient database access.
4. Improved productivity.
5. Better maintainability.

8. HQL (Hibernate Query Language)


HQL stands for Hibernate Query Language. It is an object-oriented query language used to retrieve
data from the database.
Unlike SQL, HQL works with Java classes and objects rather than tables and columns.
Features of HQL
• Database independent.
• Object-oriented.
• Similar to SQL.
• Supports inheritance.
• Portable.
Examples
Retrieve all records:
FROM Student
Retrieve specific record:
FROM Student WHERE id=1
Select specific field:
SELECT name FROM Student
Delete record:
DELETE FROM Student WHERE id=1
Advantages of HQL
1. Database independent.
2. Easy to learn.
3. Object-oriented.
4. Reduces SQL dependency.
5. Improves portability.
Disadvantages
1. Less flexible than SQL.
2. Learning required.
3. Hibernate dependent.

9. Advantages of Hibernate
Hibernate provides several advantages over traditional database programming.
Advantages
1. Reduces SQL coding.
2. Supports Object Relational Mapping.
3. Database independent.
4. Automatic table generation.
5. Provides transaction management.
Disadvantages
1. Requires learning.
2. More memory usage.
3. Slower for small applications.
4. Additional configuration required.

10. Hibernate vs JDBC


Hibernate and JDBC are both used for database connectivity, but Hibernate provides a higher level of
abstraction.
Hibernate JDBC
Hibernate is an ORM framework. JDBC is a Java API.
Requires less coding. Requires more coding.
Uses HQL. Uses SQL.
Automatic table mapping. Manual table mapping.
Database independent. Database dependent.
Provides caching. No caching support.
Higher productivity. Lower productivity.
Advantages of Hibernate over JDBC
1. Less code writing.
2. Automatic object mapping.
3. Better performance through caching.
4. Database independence.
5. Simplified transaction management.
6. Easier maintenance.
7. Higher productivity.
Disadvantages of Hibernate over JDBC
1. More memory consumption.
2. Learning curve.
3. Slower for simple applications.

Conclusion
Hibernate is an ORM framework that simplifies database programming by reducing SQL coding and
providing automatic object mapping. Components such as SessionFactory, Session, Transaction,
CRUD operations, and HQL make Hibernate a powerful framework for enterprise application
development.

You might also like