[go: up one dir, main page]

0% found this document useful (0 votes)
15 views27 pages

Understanding Java EE: Unit 1

Uploaded by

Priya Yadav
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)
15 views27 pages

Understanding Java EE: Unit 1

Uploaded by

Priya Yadav
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/ 27

Unit 1

Understanding Java EE: What is an Enterprise Application? What is java enterprise edition? Java EE
Technologies, Java EE evolution, Glassfish server Java EE Architecture,
Server and Containers: Types of System Architecture, Java EE Server, Java EE Containers.
Introduction to Java Servlets: The Need for Dynamic Content, Java Servlet Technology, Why Servlets?
What can Servlets do?
Servlet API and Lifecycle: Java Servlet API, The Servlet Skeleton, The Servlet Life Cycle, A Simple
Welcome
Servlet Working with Servlets: Getting Started, Using Annotations Instead of Deployment Descriptor.
Working with Databases: What Is JDBC? JDBC Architecture, Accessing Database, The Servlet GUI and
Database Example.

Understanding Java EE

What is an Enterprise Application?

An Enterprise Application is a large-scale software solution designed to meet the needs of an


organization, often incorporating multiple components and requiring robust architecture. These
applications are typically distributed, scalable, and maintainable, designed for handling
transactions, user management, and integrating with various systems.

What is Java Enterprise Edition (Java EE)?

Java EE is a set of specifications that extend the Java SE (Standard Edition) with specifications
for enterprise features such as distributed computing and web services. It provides a runtime
environment and API for developing and running large-scale, multi-tiered, scalable, and secure
network applications.

Java EE Technologies

Java EE encompasses various technologies, including:

• Servlets: For handling HTTP requests and responses.


• JavaServer Pages (JSP): For generating dynamic web content.
• Enterprise JavaBeans (EJB): For building scalable, transactional, and multi-user secure
applications.
• Java Persistence API (JPA): For managing relational data in Java applications.
• Java Message Service (JMS): For messaging between applications.
• Context and Dependency Injection (CDI): For managing lifecycle and interactions of
components.

Java EE Evolution

Java EE has evolved from earlier versions (like J2EE) to the latest Jakarta EE, which focuses on
microservices, cloud-native architecture, and modularity.
GlassFish Server

GlassFish is an open-source application server project, the reference implementation of Jakarta


EE (formerly Java EE). It supports the full stack of Java EE technologies, offering features like
easy deployment, administration, and monitoring tools.

Java EE Architecture

Server and Containers

• Types of System Architecture:


o Monolithic: A single-tiered software application where all components are
interconnected.
o Microservices: A distributed architecture where applications are composed of
loosely coupled services.
• Java EE Server: A server that provides an environment for deploying and running Java
EE applications. It includes services for transaction management, security, and persistence.
• Java EE Containers: These manage the execution of components, handling the lifecycle,
security, and transaction management.
o Web Container: Manages servlets and JSPs.
o EJB Container: Manages the lifecycle of EJBs.

Introduction to Java Servlets

The Need for Dynamic Content

Web applications often need to generate dynamic content based on user input or other parameters,
which is where servlets come in.

Java Servlet Technology

Servlets are Java classes that handle HTTP requests and generate dynamic responses, functioning
on a web server.

Why Servlets?

• They are platform-independent.


• Provide a robust way to manage sessions and transactions.
• Support concurrent request handling.

What can Servlets do?

• Process form data.


• Manage sessions.
• Generate dynamic web pages.
Servlet API and Lifecycle

Java Servlet API

The Servlet API provides the classes and interfaces necessary for creating servlets, including
HttpServlet, which provides methods for handling GET and POST requests.

The Servlet Skeleton

A basic servlet typically extends HttpServlet and overrides methods like doGet() and doPost().

The Servlet Life Cycle

1. Loading and Instantiation: The servlet class is loaded.


2. Initialization: The init() method is called to initialize the servlet.
3. Request Handling: The service() method handles requests, usually delegating to
doGet() or doPost().
4. Destruction: The destroy() method is called to free resources.

A Simple Welcome Servlet

A basic example of a servlet that responds with a welcome message might look like this:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Welcome to Java EE!</h1>");
}
}

Working with Servlets

Getting Started

To get started with servlets, set up a Java EE environment, create a dynamic web project, and
configure your web.xml or use annotations.

Using Annotations Instead of Deployment Descriptor

Java EE supports annotations like @WebServlet to define servlet configuration directly in the code,
making deployment descriptor (web.xml) optional.
Working with Databases

What Is JDBC?

JDBC (Java Database Connectivity) is an API for connecting and executing queries with databases
from Java applications.

JDBC Architecture

It consists of two major components:

1. JDBC API: For application-level interactions.


2. JDBC Driver API: For database-specific driver implementations.

Accessing Database

To access a database:

1. Load the driver.


2. Establish a connection.
3. Create a statement.
4. Execute queries.
5. Process results.

The Servlet GUI and Database Example

Combining servlets with JDBC allows you to create a web application that interacts with a
database. A servlet could process form data submitted by a user and store it in a database or retrieve
data to display to the user.
Unit 2

Request Dispatcher: Resquestdispatcher Interface, Methods of Requestdispatcher,


equestdispatcher Application.
COOKIES: Kinds of Cookies, Where Cookies Are Used? CreatingCookies Using Servlet,
Dynamically Changing the Colors of A Page
SESSION: What Are Sessions? Lifecycle of Http Session, Session Tracking With Servlet API, A
Servlet Session Example
Working with Files: Uploading Files, Creating an Upload File Application, Downloading Files,
Creating a Download File Application.
Working with Non-Blocking I/O: Creating a Non-Blocking Read Application, Creating The Web
Application, Creating Java Class, Creating Servlets, Retrieving The File, Creating index.jsp

Request Dispatcher

RequestDispatcher Interface

The RequestDispatcher interface in Java EE is used to forward requests and responses between
servlets or JSPs. It allows the server to send a request to another resource (like another servlet or
JSP) on the server.

Methods of RequestDispatcher

1. forward(ServletRequest request, ServletResponse response): This method forwards the


request from one servlet to another resource. After forwarding, the original servlet does not
continue processing.
2. include(ServletRequest request, ServletResponse response): This method includes the
content of another resource (like a servlet or JSP) in the response. The original servlet
continues processing after the inclusion.

RequestDispatcher Application

You can use the RequestDispatcher to manage complex requests. For example, you can collect
data in one servlet and pass it to another for further processing or display.

// Example of forwarding a request


RequestDispatcher dispatcher = request.getRequestDispatcher("targetServlet");
dispatcher.forward(request, response);
Cookies

Kinds of Cookies

1. Session Cookies: Temporary cookies that are deleted when the user closes the browser.
2. Persistent Cookies: Remain on the user's device for a specified period.

Where Cookies Are Used?

Cookies are commonly used for:

• User authentication
• Tracking user preferences
• Maintaining user sessions

Creating Cookies Using Servlet

You can create and send cookies in servlets like this:

Cookie cookie = new Cookie("username", "JohnDoe");


cookie.setMaxAge(60*60); // Set cookie to expire in 1 hour
response.addCookie(cookie);

Dynamically Changing the Colors of a Page

You can use cookies to store user preferences, such as background color, and retrieve it to change
the page dynamically:

// On page load
Cookie[] cookies = request.getCookies();
String bgColor = "white"; // default color
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("bgColor".equals(cookie.getName())) {
bgColor = cookie.getValue();
}
}
}
response.getWriter().println("<body style='background-color:" + bgColor +
"'>");
// Provide options to change color
Session

What Are Sessions?

A session represents a series of interactions between a user and a web application. It allows the
application to maintain state across multiple requests.

Lifecycle of HttpSession

1. Creation: A session is created when a user first accesses the application.


2. Tracking: The server tracks the session using a unique session ID.
3. Expiration: The session may expire after a certain period of inactivity.

Session Tracking with Servlet API

You can manage sessions using the HttpSession object in your servlet:

HttpSession session = request.getSession();


session.setAttribute("user", "JohnDoe");

A Servlet Session Example

Here’s how you might use sessions in a servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
HttpSession session = request.getSession();
String user = (String) session.getAttribute("user");
if (user == null) {
session.setAttribute("user", "JohnDoe");
response.getWriter().println("Welcome, new user!");
} else {
response.getWriter().println("Welcome back, " + user);
}
}
Working with Files

Uploading Files

You can handle file uploads in servlets using libraries like Apache Commons FileUpload or the
Servlet 3.0 API.

Creating an Upload File Application

1. Create an HTML form for file upload:

<form action="upload" method="post" enctype="multipart/form-data">


Select file: <input type="file" name="file">
<input type="submit" value="Upload">
</form>

2. In the servlet, process the uploaded file:

// Using Servlet 3.0 API


@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName =
Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
File file = new File("uploads/" + fileName);
filePart.write(file.getAbsolutePath());
response.getWriter().println("File uploaded successfully!");
}
}

Downloading Files

To facilitate file downloads, you typically set the content type and headers in your servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
File file = new File("path/to/file");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" +
file.getName() + "\"");

try (FileInputStream in = new FileInputStream(file);


OutputStream out = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}

Working with Non-Blocking I/O

Creating a Non-Blocking Read Application

In Java EE, non-blocking I/O (NIO) can be achieved using the java.nio package, which provides
capabilities for handling file and network operations asynchronously.

Creating the Web Application

1. Set up a basic web application using servlets.


2. Implement non-blocking file read/write operations using NIO.

Creating Java Class

Create a class that performs non-blocking I/O:

import java.nio.file.*;
import java.nio.channels.*;
import java.io.IOException;

public class NonBlockingFileReader {


public String readFile(String filePath) throws IOException {
Path path = Paths.get(filePath);
try (AsynchronousFileChannel fileChannel =
AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
Future<Integer> result = fileChannel.read(buffer, 0);
// Handle result here
return new String(buffer.array()).trim();
}
}
}

Creating Servlets

Integrate your NIO functionality in a servlet to respond to HTTP requests:

public class NonBlockingFileServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
NonBlockingFileReader reader = new NonBlockingFileReader();
String content = reader.readFile("path/to/file.txt");
response.getWriter().println(content);
}
}
Creating index.jsp

Create a simple JSP page to interact with your servlets:

<!DOCTYPE html>
<html>
<head>
<title>File Read Example</title>
</head>
<body>
<h1>Non-Blocking File Read</h1>
<form action="nonBlockingFile" method="get">
<input type="submit" value="Read File">
</form>
</body>
</html>
Unit 3

Introduction To Java Server Pages: Why use Java Server Pages? Disadvantages Of JSP, JSP v\s Servlets,
Life Cycle of a JSP Page, How does a JSP function? How doesJSP execute? AboutJava Server Pages
Getting Started With Java Server Pages: Comments, JSP Document, JSP Elements, JSP GUI Example.
Action Elements: Including other Files, Forwarding JSP Page to Another Page, Passing Parameters for
other Actions, Loading a Javabean.
Implicit Objects, Scope and El Expressions: Implicit Objects, Character Quoting Conventions, Unified
Expression Language [Unified El], Expression Language.
Java Server Pages Standard Tag Libraries: What is wrong in using JSP Scriptlet Tags? How JSTL Fixes
JSP Scriptlet's Shortcomings? Disadvantages OfJSTL, Tag Libraries.

Introduction to Java Server Pages

Why Use Java Server Pages?

Java Server Pages (JSP) allow developers to create dynamic web content easily by embedding
Java code directly into HTML. JSP offers several advantages:

• Separation of Concerns: It allows the separation of HTML/CSS from Java code, making
the code more maintainable.
• Reusable Components: JSP supports the use of reusable components and custom tags.
• Integration with Java: JSP can seamlessly integrate with Java code, leveraging Java’s
capabilities for server-side processing.

Disadvantages of JSP

• Complexity: Can become complex with too much embedded Java code, leading to
maintenance challenges.
• Performance: JSPs are compiled to servlets, which may incur a slight overhead.
• Debugging: Debugging JSP can be more difficult compared to standard Java applications
due to the mix of HTML and Java code.

JSP vs. Servlets

• Syntax: JSP is more concise and easier to write for generating HTML content. Servlets
require more boilerplate code.
• Use Case: JSP is primarily used for view components in MVC architecture, while servlets
handle business logic and control flow.

Life Cycle of a JSP Page

1. Translation: The JSP page is translated into a servlet by the JSP engine.
2. Compilation: The servlet is compiled into bytecode.
3. Loading: The servlet is loaded into memory.
4. Initialization: The init() method is called.
5. Request Handling: The service() method processes requests.
6. Destruction: The destroy() method is called when the servlet is removed from memory.

How Does a JSP Function?

When a JSP page is requested:

1. The server checks if the JSP needs to be compiled.


2. If it does, the server translates it to a servlet and compiles it.
3. The servlet then handles incoming requests, generating dynamic content.

How Does JSP Execute?

JSP execution involves converting the JSP code into a servlet, which the web container executes
to handle HTTP requests and responses.

Getting Started with Java Server Pages

Comments

You can use JSP comments that are not sent to the client:

<%-- This is a JSP comment --%>

JSP Document

A basic JSP document starts with a declaration and can include directives and scriptlets.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<html>
<body>
<h1>Hello, JSP!</h1>
</body>
</html>

JSP Elements

• Directives: Define global settings (e.g., <%@ page ... %>).


• Declarations: Declare variables and methods.
• Scriptlets: Embed Java code within HTML.

JSP GUI Example

A simple JSP page that displays user input could look like this:

<%@ page language="java" %>


<html>
<body>
<h2>User Input</h2>
<form action="processInput.jsp" method="post">
Enter your name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>

Action Elements

Including Other Files

You can include other JSP files or static content using the <jsp:include> tag:

<jsp:include page="header.jsp" />

Forwarding JSP Page to Another Page

You can forward a request to another JSP page:

<jsp:forward page="nextPage.jsp" />

Passing Parameters for Other Actions

You can pass parameters when including or forwarding:

<jsp:include page="anotherPage.jsp">
<jsp:param name="paramName" value="paramValue" />
</jsp:include>

Loading a JavaBean

You can use the <jsp:useBean> tag to create or retrieve a JavaBean:

<jsp:useBean id="myBean" class="com.example.MyBean" scope="session" />

Implicit Objects, Scope, and EL Expressions

Implicit Objects

JSP provides several implicit objects (e.g., request, response, session, application, out,
config, pageContext, page) that simplify development.

Character Quoting Conventions

To include special characters in JSP, you can use character entities, e.g., &lt; for <.
Unified Expression Language (Unified EL)

Unified EL allows easier access to data stored in JavaBeans and other objects. It uses a simple
syntax:

${myBean.propertyName}

Java Server Pages Standard Tag Libraries (JSTL)

What is Wrong with Using JSP Scriptlet Tags?

Scriptlet tags mix Java code with HTML, making the code harder to read, maintain, and debug.
They can lead to a cluttered design and violate the separation of concerns.

How JSTL Fixes JSP Scriptlet's Shortcomings

JSTL provides a set of tags for common tasks (like looping and conditional execution) without
embedding Java code directly in JSPs. This promotes cleaner and more maintainable code.

Disadvantages of JSTL

• Learning Curve: Developers need to learn JSTL tags and their syntax.
• Limited Control: While JSTL simplifies many tasks, it may limit the flexibility of custom
logic compared to pure Java code.

Tag Libraries

JSTL includes various standard tags:

• Core Tags: For iteration and conditionals (e.g., <c:forEach>, <c:if>).


• Formatting Tags: For formatting numbers and dates.
• SQL Tags: For database operations.

Using JSTL is recommended for better organization and maintenance of JSP files. Here’s an
example of using JSTL:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<c:forEach var="item" items="${items}">
<p>${item}</p>
</c:forEach>
Unit 4
Introduction To Enterprise Javabeans: Enterprise Bean Architecture, Benefits of Enterprise Bean, Types of
Enterprise Bean, Accessing Enterprise Beans, Enterprise Bean Application, Packaging Enterprise Beans
Working with Session Beans: When to use Session Beans? Types of Session Beans, Remote and Local
Interfaces, Accessing Interfaces, Lifecycle of Enterprise Beans, Packaging Enterprise Beans, Example of
Stateful Session Bean, Example of Stateless Session Bean, Example of Singleton Session Beans.
Working with Message Driven Beans: Lifecycle of a Message Driven Bean, Uses of Message Driven Beans,
The Message Driven Beans Example.
Interceptors: Request and Interceptor, Defining An Interceptor, AroundInvoke Method, Applying
Interceptor, Adding An Interceptor To An Enterprise Bean, Build and Run the Web Application.
Java Naming and Directory Interface: What is Naming Service? What is Directory Service? What is Java
Naming and Directory interface? Basic Lookup, JNDI Namespace in Java EE, Resources and JNDI,
Datasource Resource Definition in Java EE.

Introduction to Enterprise JavaBeans (EJB)

Enterprise Bean Architecture

Enterprise JavaBeans (EJB) is a server-side software component that encapsulates business logic
of an application. EJBs are designed to be scalable, transactional, and secure. The architecture
consists of:

• EJB Container: Manages the lifecycle of EJBs, handles transactions, security, and
concurrency.
• EJB Components: Include Session Beans, Message-Driven Beans, and Entity Beans
(though Entity Beans are less commonly used now, having been largely replaced by JPA).

Benefits of Enterprise Beans

• Scalability: EJBs can scale easily in distributed environments.


• Transaction Management: Built-in support for handling transactions automatically.
• Security: Provides a robust security model, including authentication and authorization.
• Concurrency: Manages concurrent access to shared resources.

Types of Enterprise Beans

1. Session Beans: Represent a single client and can be stateful or stateless.


2. Message-Driven Beans (MDBs): Handle asynchronous messages from a message broker
(e.g., JMS).
3. Entity Beans: Historically used for persistence (largely replaced by JPA).

Accessing Enterprise Beans


Enterprise Beans can be accessed through:

• Remote Interfaces: For clients in different JVMs.


• Local Interfaces: For clients within the same JVM.

Enterprise Bean Application

An enterprise bean application is typically structured with business logic encapsulated in beans,
accessed through client applications, often utilizing a client-side Java EE technology such as
servlets or JSP.

Packaging Enterprise Beans

EJBs are packaged in JAR files, typically structured as:

• A META-INF directory containing the ejb-jar.xml descriptor.


• Class files for the beans and their interfaces.

Working with Session Beans

When to Use Session Beans?

Use session beans for operations that are specific to a user or a session, such as processing
transactions or maintaining state.

Types of Session Beans

1. Stateful Session Beans: Maintain state across multiple method calls.


2. Stateless Session Beans: Do not maintain state; they handle requests independently.
3. Singleton Session Beans: A single instance shared across all clients.

Remote and Local Interfaces

• Local Interfaces: Used when the client and EJB are in the same application.
• Remote Interfaces: Used for accessing EJBs across different applications.

Accessing Interfaces

Client code can look up EJBs using JNDI:

Context ctx = new InitialContext();


MySessionBeanRemote remoteBean = (MySessionBeanRemote)
ctx.lookup("java:global/myapp/MySessionBean!com.example.MySessionBeanRemote")
;
Lifecycle of Enterprise Beans

The lifecycle of a session bean typically includes:

1. Instantiation: The EJB container creates the bean instance.


2. Initialization: The @PostConstruct method is called.
3. Business Method Invocation: Client calls business methods.
4. Removal: The container removes the bean instance.

Packaging Enterprise Beans

Session beans are packaged in JAR files and deployed on an EJB container.

Example of Stateful Session Bean

@Stateful
public class ShoppingCartBean implements ShoppingCart {
private List<Item> items = new ArrayList<>();

public void addItem(Item item) {


items.add(item);
}

public List<Item> getItems() {


return items;
}
}

Example of Stateless Session Bean

@Stateless
public class CalculatorBean implements Calculator {
public int add(int a, int b) {
return a + b;
}
}

Example of Singleton Session Beans

@Singleton
public class ConfigurationManager {
private Properties properties;

@PostConstruct
public void init() {
// Load properties
}

public String getProperty(String key) {


return properties.getProperty(key);
}
}
Working with Message Driven Beans

Lifecycle of a Message Driven Bean

1. Instantiation: Created by the container.


2. Message Processing: The onMessage() method is invoked when a message arrives.
3. Removal: The bean can be removed by the container.

Uses of Message Driven Beans

MDBs are used for processing messages from message queues (e.g., JMS) asynchronously, such
as handling notifications or background tasks.

Message Driven Beans Example

java
Copy code
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue
= "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destination", propertyValue =
"myQueue")
})
public class MyMessageBean implements MessageListener {
public void onMessage(Message message) {
// Process the message
}
}

Interceptors

Request and Interceptor

Interceptors allow you to define cross-cutting concerns, such as logging or transaction


management, without modifying the business logic.

Defining an Interceptor

You define an interceptor class and annotate methods with @AroundInvoke to specify the
interception point.

@Interceptor
public class LoggingInterceptor {
@AroundInvoke
public Object logMethod(InvocationContext context) throws Exception {
System.out.println("Method called: " + context.getMethod().getName());
return context.proceed();
}
}
Applying Interceptor

You apply interceptors to EJBs using annotations:

@Interceptors(LoggingInterceptor.class)
@Stateless
public class MyService {
public void doSomething() {
// Business logic
}
}

Adding an Interceptor to an Enterprise Bean

Interceptors can be specified at the class or method level, allowing for flexible logging or
processing.

Build and Run the Web Application

Compile your EJB project, package it as a JAR, and deploy it to an EJB container or application
server (like GlassFish or WildFly).

Java Naming and Directory Interface (JNDI)

What is Naming Service?

A naming service allows clients to look up resources and services in a distributed environment
using names.

What is Directory Service?

A directory service provides a way to store and retrieve attributes associated with objects, such as
user information.

What is Java Naming and Directory Interface?

JNDI is an API that provides naming and directory functionality, allowing Java applications to
look up and interact with various resources like EJBs, databases, and more.

Basic Lookup

Basic lookup using JNDI involves obtaining a context and calling the lookup() method:

Context ctx = new InitialContext();


MyBean myBean = (MyBean) ctx.lookup("java:global/myapp/MyBean");
JNDI Namespace in Java EE

The JNDI namespace in Java EE provides a structured way to store and access resources, including
EJBs, DataSources, and environment entries.

Resources and JNDI

Resources like databases and connection pools are defined in the server’s configuration and
accessed via JNDI.

Datasource Resource Definition in Java EE

In a Java EE environment, data sources are defined in context.xml or persistence.xml,


enabling applications to look them up using JNDI:

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
Unit 5
Persistence, Object/Relational Mapping And JPA: What is Persistence? Persistence in Java, Current
Persistence Standards in Java, Why another Persistence Standards? Object/Relational Mapping,
Introduction to Java Persistence API: The Java Persistence API, JPA, ORM, Database and the Application,
Architecture of JPA, How JPA Works? JPA Specifications.
Writing JPA Application: Application Requirement Specifications, Software Requirements, The
Application Development Approach, Creating Database and Tables in Mysql, creating a Web Application,
Adding the Required Library Files, creating a Javabean Class, Creating Persistence Unit [Persistence.Xml],
Creating JSPS, The JPA Application Structure, Running the JPA Application.
Introduction to Hibernate: What is Hibernate? Why Hibernate? Hibernate, Database and The Application,
Components of Hibernate, Architecture of Hibernate, How Hibernate Works? Writing Hibernate
Application: Application Requirement Specifications, Software Requirements, The Application
Development Approach, Creating Database and Tables in Mysql, creating a WebApplication, Adding the
Required Library Files, creating a Javabean Class, Creating Hibernate Configuration File, Adding a
Mapping Class, Creating JSPS, Running The Hibernate Application.

Persistence, Object/Relational Mapping, and JPA

What is Persistence?

Persistence refers to the ability of a system to retain data across sessions, ensuring that data can be
saved and retrieved when needed. In software development, it typically involves storing data in a
database.

Persistence in Java

In Java, persistence is achieved using various APIs and frameworks that allow developers to
interact with databases easily. This includes direct JDBC usage, as well as higher-level abstractions
like JPA and Hibernate.

Current Persistence Standards in Java

• JDBC: The traditional API for database interaction.


• JPA (Java Persistence API): A specification that provides a framework for managing
relational data in Java applications.

Why Another Persistence Standard?

JPA was created to provide a standardized approach to ORM in Java, addressing the complexities
of JDBC and allowing developers to focus on their domain model rather than the underlying
database operations.
Object/Relational Mapping (ORM)

ORM is a technique that allows developers to interact with a database using objects rather than
SQL queries. It maps database tables to Java classes and columns to class attributes, simplifying
data manipulation.

Introduction to Java Persistence API (JPA)

The Java Persistence API

JPA is a Java specification for managing relational data in applications. It defines how to perform
CRUD (Create, Read, Update, Delete) operations using a set of annotations and an EntityManager
interface.

ORM and Database Interaction

JPA provides an abstraction layer over the database, allowing developers to work with Java objects
without needing to write extensive SQL queries.

Architecture of JPA

• Entity: A lightweight persistent domain object.


• EntityManager: The main interface for interacting with the persistence context.
• Persistence Context: A set of entity instances managed by an EntityManager.
• EntityManagerFactory: A factory for creating EntityManager instances.

How JPA Works

1. Entity Mapping: Define entities using annotations or XML.


2. Persistence Context: Use an EntityManager to manage entities.
3. Query Language: Use JPQL (Java Persistence Query Language) for querying entities.

JPA Specifications

JPA provides several specifications for entity relationships, transactions, and querying, ensuring a
standard approach across different implementations.

Writing a JPA Application

Application Requirement Specifications

Define what the application needs to do, such as managing users, products, or any domain-specific
data.
Software Requirements

• Java Development Kit (JDK)


• JPA implementation (like Hibernate or EclipseLink)
• A relational database (like MySQL)

The Application Development Approach

1. Define entities and relationships.


2. Create the database schema.
3. Develop the application logic using JPA.

Creating Database and Tables in MySQL

Use SQL commands or a database management tool to create the necessary tables for your
application.

Creating a Web Application

Set up a web application using a Java EE server or a framework like Spring.

Adding the Required Library Files

Include JPA and database driver libraries in your project. For Maven, you would include
dependencies in your pom.xml.

Creating a JavaBean Class

Define your entity class with JPA annotations:

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String email;

// Getters and setters


}

Creating Persistence Unit (persistence.xml)

Define your persistence unit in persistence.xml:

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">


<persistence-unit name="myPU">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.User</class>
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/mydb"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password"
value="password"/>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>

Creating JSPs

Create JSP pages to interact with your JPA entities, allowing users to create, read, update, or delete
records.

The JPA Application Structure

Your application structure typically includes:

• Entities: Java classes annotated with JPA annotations.


• Persistence Configuration: persistence.xml.
• JSPs: Web pages for user interaction.

Running the JPA Application

Deploy your application on a server (like Tomcat) and access it through a web browser.

Introduction to Hibernate

What is Hibernate?

Hibernate is an open-source ORM framework that implements the JPA specification. It simplifies
database interactions by providing a powerful query language (HQL) and supports complex
mappings.

Why Hibernate?

• Ease of Use: Simplifies data handling with automatic mapping.


• Performance: Offers features like caching and batch processing.
• Flexibility: Supports various database platforms.
Hibernate, Database, and The Application

Hibernate acts as a bridge between Java applications and the database, handling CRUD operations
and managing transactions.

Components of Hibernate

1. Configuration: Specifies database connection details and mapping information.


2. Session: Represents a single unit of work with the database.
3. Transaction: Manages database transactions.

Architecture of Hibernate

• SessionFactory: Creates sessions for interacting with the database.


• Session: Provides methods to perform CRUD operations.
• Transaction: Allows for transaction management.

How Hibernate Works

1. Configuration: Set up Hibernate using XML or annotations.


2. Session Management: Use sessions to manage database interactions.
3. Transaction Handling: Wrap operations in transactions to ensure data integrity.

Writing a Hibernate Application

Application Requirement Specifications

Define your application's requirements, such as what entities you need and how they will interact.

Software Requirements

• Java Development Kit (JDK)


• Hibernate libraries
• A relational database (like MySQL)

The Application Development Approach

1. Create entity classes.


2. Configure Hibernate settings.
3. Develop application logic using Hibernate APIs.

Creating Database and Tables in MySQL

Use SQL commands or a management tool to set up your database.


Creating a Web Application

Set up your web application structure.

Adding the Required Library Files

Include Hibernate and JDBC driver libraries in your project.

Creating a JavaBean Class

Define your Hibernate entity class:

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;


private String email;

// Getters and setters


}

Creating Hibernate Configuration File

Create a hibernate.cfg.xml file for configuration:

<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">password</property>
<mapping class="com.example.User"/>
</session-factory>
</hibernate-configuration>

Adding a Mapping Class

In your configuration, ensure your entity classes are mapped to database tables.

Creating JSPs

Create JSP pages for user interaction, similar to the JPA application.
Running the Hibernate Application

Deploy your Hibernate application on a server and test its functionality through the web interface.

You might also like