Advance Java
Advance Java
Day 1:
📘 What is JDBC?
✅ Key Features:
Platform-independent (thanks to Java)
JDBC (Java Database Connectivity) is an API provided by the [Link] module (introduced in Java
9's module system). It allows Java applications to connect to and interact with relational databases.
📦 JDBC-related Packages
1. [Link] – Standard DB connectivity (basic JDBC features)
❓ Why JDBC?
Enables Java apps to communicate with databases
JDBC drivers
2. Database URL
3. Username
4. Password
🧱 JDBC Architecture
JDBC API provides interfaces ( Connection , Statement , ResultSet , etc.)
2. Establish Connection:
3. Create Statement/PreparedStatement
5. Process ResultSet
🧪 Examples
Login without Layers:
Using Layers:
Tester
POJO (User)
🧭 CRUD Objectives
1. Display all user details
2. Login validation
5. Update password
6. Delete customer
Driver Layer: DB vendors implement these interfaces (e.g., [Link] for MySQL).
[Link]("[Link]");
3. Establish Connection
5. Execute Query
6. Process ResultSet
7. Close Resources
Always close ResultSet , Statement , and Connection (preferably in finally or use try-with-
resources).
✅ PreparedStatement vs Statement:
Feature Statement PreparedStatement
✅ Transaction Management:
To group multiple SQL operations into a single atomic unit:
[Link](false);
try {
// execute multiple queries
[Link]();
} catch(SQLException e) {
[Link]();
}
✅ Metadata in JDBC:
DatabaseMetaData — info about DB, tables, driver
✅ Complete DB Independence:
Use a .properties file to store DB config (driver, URL, username, password). Load with:
❌ Vulnerable Example:
String sql = "SELECT * FROM users WHERE user_name = '" + uname + "' AND password = '" +
pass + "'";
Statement st = [Link]();
[Link](sql);
uname: a
pass: b' OR '1'='1
SELECT * FROM users WHERE user_name = 'a' AND password = 'b' OR '1'='1';
SQL statements are precompiled, and user inputs are treated as data, not part of the SQL
command.
The database sees the query structure and the data separately, making injections impossible.
Least Privilege Principle: Use database accounts with limited access rights.
Stored Procedures (with care): Preferably those that do not dynamically build queries.
ORM Frameworks: Consider using Hibernate, JPA, etc., which abstract away SQL.
Use Web Security Tools: Periodically scan your app with tools like OWASP ZAP or SQLMap.
Sends HTTP Request: Uses a URL like [Link] to send a request to the server.
Manages:
Servlets
JSP
JavaBeans
DAO
Utils
Sessions
Method (GET/POST)
URL
Headers
Cookies
🔸 HTTP Response:
1. Status Code (100–500 range):
2XX : Success
3XX : Redirection
2. Headers:
3. Body:
2. If not present:
3. On subsequent requests:
Server uses it to retrieve the session object and maintain user state (e.g., login info,
shopping cart).
✅ Summary
Web clients make requests to web apps hosted on a Java web server.
Day 3:
3. Update stock
If any of these steps fail, the entire transaction must be rolled back.
Connection cn = [Link](...);
[Link](false); // Start transaction
try {
// Business logic with multiple SQL statements
// Step 1: Check product
// Step 2: Update credit
// Step 3: Update stock
7. Rollback to Savepoint
🔍 What is CallableStatement ?
In JDBC, CallableStatement is an interface used to call stored procedures and functions defined in
your database. These are like pre-written SQL blocks stored on the database server.
📦 Real-Life Analogy
Imagine a restaurant kitchen (the database). Instead of telling the chef every step for cooking a
dish (writing SQL every time), you just place an order (call a stored procedure), like:
Here, you're calling a predefined recipe (stored procedure) and passing parameters like "with
cheese" or "no onions".
original_price (IN)
discount_percent (IN)
import [Link].*;
// Step 3: Execute
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
📝 Notes
IN parameters → You set values using .setType() .
Return values from stored functions use the ?=call funcName(...) format.
Answer: I set their value with setType() and also register their type using registerOutParameter() before
executing the statement.
✅ What is a Servlet?
A Servlet is a Java class used to build dynamic web applications. It runs on a Java-enabled web
server (like Tomcat) and handles HTTP requests and responses.
Think of it as a Java program that listens to browser requests and sends back responses (like
HTML, JSON, etc).
✅100%
Why is declared as abstract, even though it has
HttpServlet
concrete methods?
✔ Full Explanation:
1. It’s abstract to enforce a design pattern
Even though all methods in HttpServlet have real (concrete) implementations, it’s marked abstract
So, it’s mandatory for developers to override at least one of them ( doGet() , doPost() , etc.) depending
on your application's need.
3. Why not just make the methods abstract instead of the whole class?
Because:
Some default behavior (e.g., service() method) is reusable and implemented concretely.
You don’t have to override every method — just the one(s) you need (e.g., only doPost() ).
Making the whole class abstract prevents someone from accidentally instantiating a servlet
without overriding anything — which would be a programming error.
🧠 Summary
Feature Purpose
Default methods exist So you only override what you need (e.g., doGet , doPost )
Prevents programming error Ensures developer must override relevant HTTP method(s)
✅ Real-world Analogy
Think of HttpServlet like a template form:
“You must fill in at least one section (like doGet) before using this!”
🔧 2. Initialization ( init() )
Called once after the servlet is instantiated.
The init(ServletConfig config) method is called to allow the servlet to initialize resources (e.g., DB
connection, file reading, etc.).
@Override
public void init() throws ServletException {
It determines the HTTP method (GET, POST, etc.) and dispatches it to the correct handler
method ( doGet() , doPost() , etc.).
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Serv
letException, IOException {
// Handle GET request
}
📌 Note:
You generally override doGet() or doPost() rather than service() itself.
🛑 4. Destruction ( destroy() )
Called once when the servlet is being removed (e.g., on server shutdown or redeployment).
@Override
public void destroy() {
// Cleanup code
}
✅ Code:
[Link]("admin_page");
GET /context_path/admin_page
⚠ Caveat:
RequestDispatcher rd = [Link]("next_page");
✅ Code:
[Link](request, response);
🔍 Details:
Response buffer cleared before forwarding.
⚠ Caveat:
Throws IllegalStateException if response already committed.
✅ Code:
[Link](request, response);
🔍 Details:
Used for reusing content (e.g., header/footer).
Summary Table:
Feature Client Pull (Redirect) Server Pull (Forward) Server Pull (Include)
🧾 What is a Session?
Advance java Day Wise - Akshay 18
A session represents a conversational state between a client and server over multiple HTTP
requests/responses.
Since HTTP is stateless, sessions are used to maintain identity and state across requests (e.g.,
from login to logout).
🛒 Example: A shopping cart must know which user's cart to add items to, even across multiple
pages.
🧠 Session Duration
Typically: From login to logout or until timeout.
✅ What is a Cookie?
Small text data, created by server, stored in client's browser.
✅ Cookie Lifecycle:
1. Create Cookie:
[Link](c);
4. Control Expiry:
[Link](3600); // 1 hour
❌ Disadvantages:
Developer manually manages cookies.
✅ Steps:
1. Get/Create Session:
2. Store Attributes:
[Link]("cart", cartList);
3. Retrieve Attributes:
4. Remove Attribute:
[Link]("cart");
[Link]();
[Link]();
[Link](300); // 5 minutes
<session-config>
<session-timeout>10</session-timeout> <!-- in minutes -->
</session-config>
❌ Limitation:
If cookies are disabled, session tracking fails unless using URL rewriting.
Example:
📦 What is an Attribute?
An attribute is a key-value pair stored server-side, created by the developer:
🧭 Scopes of Attributes:
Scope Visibility
Solution: Reuse a fixed number of threads to handle many tasks = better scalability,
performance, and control.
[Link](task);
[Link]();
try {
Integer result = [Link](); // Blocks until result is ready
[Link]("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
[Link]();
}
[Link]();
Method Description
execute(Runnable) Executes a Runnable task.
submit(Callable) Submits task and returns Future .
invokeAll(Collection<Callable>) Blocks until all tasks complete.
shutdown() Initiates graceful shutdown.
shutdownNow() Attempts to stop all tasks and returns those not yet executed.
awaitTermination(timeout, unit) Blocks until termination or timeout.
🔹 Callable vs Runnable
Feature Runnable Callable
Returns a result? ❌ ✅
Throws checked exceptions? ❌ ✅
Functional interface? ✅( run() ) ✅( call() )
This ID will be sent back in every future request to the same web app.
Cookie: JSESSIONID=ABC123XYZ
[Link]();
🧠 Key Points:
Feature Detail
[Link]("[Link]");
[Link];jsessionid=ABC123XYZ
3. When Is It Created?
It is created during web application deployment time. The ServletContext object is initialized when
the web app starts, and it exists until the web app stops.
Example:
getServletContext().setAttribute("appData", someObject);
<context-param>
<param-name>user_name</param-name>
<param-value>abc</param-value>
</context-param>
You can access these parameters from any servlet in the app after it’s initialized.
You can retrieve resources like files inside your web application directory.
Set attributes that will be shared across all servlets in the web application.
getServletContext().setAttribute("appData", appData);
synchronized (getServletContext()) {
// Access shared context data
}
@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Se
rvletException, IOException {
String username = getServletContext().getInitParameter("user_name");
getServletContext().log("Retrieved user_name: " + username);
3. Servlet can retrieve the ServletContext and access context parameters, attributes, and other
resources.
📦 [Link] Overview
1. What is ServletConfig ?
ServletConfig is a servlet-specific configuration object.
These parameters are used to configure the servlet instance when it is created.
3. When Is It Created?
After the Web Container creates the servlet instance (using the default constructor), it creates
the ServletConfig object.
The ServletConfig is then passed to the servlet's init() method, which is invoked during servlet
initialization.
This is an example of Dependency Injection (DI), where the WC injects the necessary
configuration information into the servlet.
5. Usage of ServletConfig :
Store Servlet-Specific Initialization Parameters:
These parameters are specific to the servlet and cannot be accessed by other servlets.
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>init</servlet-name>
<url-pattern>/test_init</url-pattern>
</servlet-mapping>
@WebServlet(value = "/test",
initParams = {
@WebInitParam(name = "nm1", value = "val1"),
@WebInitParam(name = "nm2", value = "val2")
})
public class MyServlet extends HttpServlet {
// Servlet code
}
@Override
public void init() throws ServletException {
// Accessing the init parameters here
}
paramName) method.
Example:
Here’s an example of a servlet that uses ServletConfig to retrieve initialization parameters:
@WebServlet(value = "/test",
initParams = {
@WebInitParam(name = "username", value = "admin"),
@WebInitParam(name = "password", value = "password123")
@Override
public void init() throws ServletException {
// Access the ServletConfig object
ServletConfig config = getServletConfig();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws Se
rvletException, IOException {
// Servlet logic here
}
}
In this example:
The servlet retrieves the username and password initialization parameters using ServletConfig .
Feature Description
When Is It Created After the servlet instance is created, before init() method is called
1. ServletRequestListener
This listener allows you to react to the lifecycle of a ServletRequest object, specifically when
the request is created or destroyed.
Methods:
2. HttpSessionListener
This listener allows you to react to the lifecycle of an HTTP session, specifically when a
session is created or destroyed.
Methods:
3. ServletContextListener
This listener allows you to react to the lifecycle of the web application context, which is
essentially the entire web application. You can respond when the web application is
initialized or destroyed.
Methods:
void contextDestroyed(ServletContextEvent sce) - Invoked when the context (web app) is destroyed.
void contextInitialized(ServletContextEvent sce) - Invoked when the context (web app) is initialized.
There are other specific listener interfaces that can be used depending on the event type,
such as ServletContextAttributeListener or HttpSessionAttributeListener , which react to the addition,
removal, or modification of context or session attributes.
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
// Code to handle session creation
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// Code to handle session destruction
}
}
If you're using an older version of the Servlet API or prefer XML configuration, you can
register the listener in the [Link] configuration file.
<listener>
<listener-class>[Link]</listener-class>
</listener>
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// Code to initialize resources (e.g., database connections)
[Link]("Web Application Initialized");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Code to clean up resources (e.g., closing database connections)
[Link]("Web Application Destroyed");
}
}
In this example:
The contextInitialized method will be called when the web application is initialized.
This can be helpful for performing one-time setup tasks or cleanup operations.
Session Management: For tracking user login times or handling session timeouts.
Global Initialization: Loading global configuration or initializing services when the web
application starts.
When an HTTP
sessionCreated(HttpSessionEvent)
HttpSessionListener session is created or
sessionDestroyed(HttpSessionEvent)
destroyed
Day 7:
HTML code
✅ 2. JSP Lifecycle
The JSP lifecycle includes the following steps:
Phase Description
👉 This lifecycle ensures that your JSP page acts just like a servlet behind the scenes.
✅ 3. JSP Directives
JSP Directives provide global info about the page. They begin with <%@ and are not directly
displayed.
page <%@ page ... %> Sets properties like language , import , session , etc.
include <%@ include file="..." %> Includes a static file at translation time
taglib <%@ taglib uri="..." prefix="..." %> Enables use of custom tags like JSTL
Example:
Expression <%= expression %> Outputs the result directly into HTML
Example:
✅ 6. JavaBeans in JSP
JavaBeans are reusable Java classes that follow specific conventions (with private properties +
public getters/setters). JSP uses them to separate business logic.
Steps:
1. Use in JSP:
✅ Goal
Develop a web application independent of cookies for session tracking.
The only info the server needs from the client is the Session ID (usually JSESSIONID ).
If it’s not coming via cookie, then embed it directly in the URL.
This allows state management even when the browser doesn’t support or allow cookies.
href links
form actions
sendRedirect URLs
2. If found, the server extracts the session ID and continues session tracking normally.
Behavior:
// Example
String safeURL = [Link]("[Link]");
[Link]("<a href='" + safeURL + "'>My Profile</a>");
// sendRedirect example
String redir = [Link]("[Link]");
[Link](redir);
❌ Disadvantage
Not secure by default
Optionally:
Invalidate old session and generate a new session ID after login ( [Link]() →
[Link](true) )
🌐 JSP Overview
Covers:
Why JSP?
JSP Life-cycle
Comments:
🔸 Scripting Elements
1. Scriptlets: <% ... %>
🔸 EL Implicit Objects
Accessible only in EL ( ${} ):
🔸 JSP Directives
Used to control the overall structure of the JSP page.
Example:
🔸 JSP Actions
Standard Actions:
📌 Why JSP?
1. Separation of Presentation Logic (PL) and Business Logic (BL).
3. JSPs are not commonly used in modern full-stack apps—replaced by frontend frameworks like
React/Angular/Vue.
🌀 JSP Lifecycle:
1. Client request triggers JSP lifecycle.
6. On destroy ➜ jspDestroy() .
💡 Key Features:
✅ Implicit Objects (available in _jspService() ):
✅ Scripting Elements:
Scriptlet: <% code %>
${[Link]} ➜ [Link]("name")
✅ Directives:
<%@ page %> , <%@ include %>
✅ JSP Actions:
e.g., <jsp:useBean> , <jsp:setProperty> , <jsp:getProperty>
✅ JavaBeans in JSP:
POJO with private props, public getters/setters, default constructor.
🌀 1. Translation Phase
What happens?
Web Container translates the JSP file ( .jsp ) into a Servlet Java file ( .java ).
✅ Depends on: The .jsp file to generate the servlet source code.
Web Container loads the .class file and creates an object of the servlet.
Web Container calls the jspInit() method only once when the JSP is first loaded.
When the server is shutting down or the JSP is being undeployed, Web Container calls
jspDestroy() .
Compilation Java Compiler (via WC) — Compiler depends on .java servlet file
Request Handling Web Container _jspService(req, res) JSP depends on WC to invoke _jspService()
🧠 Key Relationships:
Web Container is the boss – it controls the full life cycle.
JSP is passive – it waits for the container to call its lifecycle methods.
JSP’s lifecycle methods ( jspInit , _jspService , jspDestroy ) are called by the container, not by the
developer.
3️⃣ Loading & Web Container Constructor of JSP Servlet Class JSP Servlet Class
Instantiation
📌 Important Notes:
✅ jspInit() :
Called by: Web Container
✅ _jspService() :
Called by: Web Container
✅ jspDestroy() :
Called by: Web Container
But if the client browser has cookies disabled, then we still need a way to track the session.
[Link]
If found, it extracts the value and uses it to fetch the session (as usual).
Use the following methods to manually encode URLs with session ID when cookies may not
be available.
🔹 Key APIs
Use Case API Called Called On Returns
🔸 Example:
// For anchor tag, form action, etc.
String encodedURL = [Link]("[Link]");
// For redirection
String redirectURL = [Link]("[Link]");
[Link](redirectURL);
Your Servlet/JSP Code [Link]("url") Encode URL with session ID for links
Your Servlet/JSP Code [Link]("url") Encode URL with session ID for redirect
Web Container Looks for JSESSIONID in cookie or URL To retrieve existing HttpSession
📝 NOTE:
If the session ID is already coming via a cookie, the container suppresses URL rewriting (no
need to duplicate session ID).
Feature Description
Source Sent by the client (from HTML form / URL query string).
Used in [Link]("key")
🧭 Example:
<form action="[Link]" method="post">
<input name="username">
</form>
Feature Description
Set by Servlet/JSP
🔹 [Link]("key", value)
Caller: Servlet/JSP sets it
🔹 [Link]("key", value)
Caller: Servlet/JSP
📌 Summary Table
Feature Parameter Attribute
Day 9
✅ What is JSTL?
JSTL is a tag-based alternative to Java code in JSP. It provides standard tags for:
Redirection
Setting/removing attributes
Conditions
Loops
🔧 Tomcat doesn't come with JSTL, so you must manually add the JSTL JAR (e.g., [Link] in
WEB-INF/lib ).
🧩 Step-by-Step Usage
Step 1: Add JSTL jar
✔️ Already done.
Step 2: Import the Core Tag Library
<c:redirect url="[Link]"/>
🔄 If cookies disabled:
[Link];jsessionid=ABC12345678
🧠 Equivalent Java:
[Link]("abc", [Link]("name"));
🧠 Equivalent Java:
[Link]("abc");
4. If Condition ( <c:if> )
🧠 Equivalent Java:
if([Link]("btn").equals("Withdraw")) {
[Link]("In Withdraw");
}
<c:choose>
<c:when test="${[Link] eq 'Withdraw'}">Withdraw</c:when>
<c:when test="${[Link] eq 'Deposit'}">Deposit</c:when>
<c:otherwise>Unknown action</c:otherwise>
</c:choose>
🧠 Equivalent Java:
6. Loop ( <c:forEach> )
🧠 Java Equivalent:
List<Item> items = (List<Item>) [Link]("items");
for(Item item : items) {
[Link](item);
}
You're referring to a common layered architecture pattern in Java web applications, particularly
when using JavaBeans, DAO (Data Access Object), and JSP (Java Server Pages). Here's a clear
breakdown of the dependency flow:
Example: A StudentBean might call [Link](id) to get data from the database.
JSP doesn't interact with DAO directly; instead, it depends on JavaBeans to get the data.
Full Flow:
[JSP] --> uses --> [JavaBean] --> calls --> [DAO] --> interacts with DB
🔍filters/session
Should you learn JSTL before advanced topics like
tracking?
Yes ✅
📌 Reason:
JSTL makes JSP cleaner and prepares you to understand:
EL (Expression Language)
MVC flow
Once you're comfortable with JSP + JSTL, you’ll naturally understand how HttpServlet , HttpSession , and
filters fit in.
Hibernate
✅ What is Hibernate?
Hibernate is an ORM (Object-Relational Mapping) tool that helps Java applications
automatically persist data in databases.
It implements JPA (Java Persistence API), which is a Java EE standard for persistence.
6. No JDBC boilerplate code: Connection handling, statement creation, result set processing is
handled internally.
Heavyweight, thread-safe.
2. Session
Holds L1 cache.
3. Configuration
Reads [Link] .
4. Transaction
✅ SessionFactory API
SessionFactory is a heavyweight object used to create Session objects in Hibernate.
✅ openSession vs getCurrentSession
Returns New Session each time Same session bound to the current context
Closes
No, needs manual close Yes, closed automatically at end of txn
Automatically
<property name="hibernate.current_session_context_class">thread</property>
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
@Lob
private byte[] image;
@Enumerated([Link])
private Role role;
}
try {
[Link](entity); // OR get/update/delete/load etc.
[Link]();
} catch (RuntimeException e) {
[Link]();
throw e;
Would you like a diagram of the Hibernate architecture or a code demo for a specific CRUD
operation?
Step-by-Step Guide
1. Create Maven Project
Open your IDE (Eclipse or IntelliJ).
Create a Maven Project with Group ID, Artifact ID, and Packaging option as jar .
2. Update [Link]
Replace the <build> and <dependencies> sections of the [Link] with the following:
<build>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>
3. Update Project
Right-click on the project → Maven → Update Project .
package utils;
import [Link];
import [Link];
static {
try {
sessionFactory = new Configuration().configure("[Link]").addAnnotatedClas
s([Link]).buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
Run this as a Java Application. You should see the output Hibernate booted..... confirming Hibernate
was initialized correctly.
import [Link].*;
import [Link];
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "dob")
private Date dob;
@Enumerated([Link])
@Column(name = "role")
private Role role;
@Lob
@Column(name = "image")
private byte[] image;
<mapping class="User"/>
import [Link];
import [Link];
@Override
public String registerUser(User user) {
Transaction transaction = null;
try (Session session = [Link]().openSession()) {
transaction = [Link]();
[Link](user);
[Link]();
return "User registered successfully";
} catch (Exception e) {
if (transaction != null) [Link]();
[Link]();
return "Error in user registration";
}
}
}
import [Link];
table in your database, and you will see a message indicating whether the user was registered
successfully.
3. Maven downloads dependencies and executes phases like compile , test , and package .
Advantages:
Consistency: Standardizes the build process.
Day 10
2. Persistent:
Changes auto-synchronized.
Ex: [Link](s);
3. Detached:
Ex: [Link]();
4. Removed:
Ex: [Link](s);
[Link]("Updated");
[Link](entity);
Delete: [Link](entity);
Typical structure:
Examples:
@Lob
private byte[] image;
1. Saving BLOB:
1. Fetching BLOB:
It compares the current state of the entities in the session with the database.
4. [Link]()
This process ensures that all changes made within a transaction are synchronized with the
database when commit() is called.
1. No [Link]()
rollback() prevents [Link]() from being called automatically.
That means changes made to entities in memory are not pushed to the database.
No SQL is executed on the database if it wasn't flushed manually before the rollback.
In short:
rollback() =
- Cancel transaction
- No DB changes
- Discard DML
- Clear session
- Return connection
0. SessionFactory API
openSession() → Opens new session. Must be explicitly closed.
saveOrUpdate(Object) → Insert (null ID), Update (existing ID), throws exception (non-existing ID).
2. Data Retrieval
get(Class, Serializable) → Returns persistent POJO or null.
Usage:
String hql = "from BookPOJO b where [Link] < :price and [Link] = :author";
List<BookPOJO> books = [Link](hql, [Link])
.setParameter("price", p)
.setParameter("author", a)
.getResultList();
String hql = "update BookPOJO b set [Link] = [Link] - :disc where [Link] = :au and [Link]
hDate < :dt";
int updated = [Link](hql)
.setParameter("disc", d)
.setParameter("au", a)
.setParameter("dt", date)
.executeUpdate();
5. Delete
[Link](Object) → Removes persistent entity from DB and L1 cache.
HQL Delete:
7. Session Methods
evict(Object) → Removes one object from L1 cache.
8. Query Enhancements
setMaxResults(int) / setFirstResult(int) → Used for pagination.
Pagination Example:
9. Named Queries
CriteriaBuilder cb = [Link]();
CriteriaQuery<Book> cq = [Link]([Link]);
Root<Book> root = [Link]([Link]);
[Link](root).where([Link]([Link]("author"), "Author Name"));
1. You invoke:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
When the session is flushed, Hibernate compares the current state of objects in memory with
the state in the database.
If differences are found, appropriate DML (Data Manipulation Language) queries (like UPDATE )
are generated and executed.
[Link]()
Manual flush:
🔎 Key Points
No explicit update() is needed after modifying a persistent object.
Hibernate does not update the DB immediately when the object is modified — changes are
queued until flush/commit.
1. Transient
2. Persistent
3. Detached
4. Removed
[Link](s)
[Link](s)
[Link](s)
To reattach:
Day 11
🔧 How It Works
When you define relationships between entities (e.g., @OneToMany , @ManyToOne , etc.), you can specify
a cascade strategy using the cascade attribute.
Now, performing an operation (e.g., save , delete ) on the Category will automatically apply that
operation to all its associated BlogPost objects.
Think of it as: “If the parent disowns a child, Hibernate should delete the
child from the database automatically.”
🔧 Where is it used?
It’s used with these annotations:
@OneToMany
@OneToOne
Even with [Link] , Hibernate doesn’t assume a child should be deleted just because it’s
removed from the list — unless orphanRemoval = true is explicitly set.
Hibernate will mark product for deletion when the transaction commits (via automatic dirty checking
and flush).
🔁 Cascade vs orphanRemoval
Deletes from DB if removed from parent
Feature Purpose
list?
[Link]
When parent is deleted, child is also
deleted
❌ (only deletes when parent is deleted)
orphanRemoval=true When child is removed from the collection ✅ (deletes orphan child automatically)
1. MappedSuperclass ( @MappedSuperclass ):
Used for common fields in a parent class that are shared across multiple entities.
No table is generated for this class. It acts as a base for other entities to inherit.
Common fields could include ID , createdDate , updatedDate , and version for optimistic locking.
Use Case:
Example:
@MappedSuperclass
public abstract class BaseEntity {
@Id
private Long id;
@CreationTimestamp
private LocalDateTime createdDate;
@UpdateTimestamp
private LocalDateTime updatedDate;
@Version
private Integer version;
}
A weaker form of association that allows one entity to "have" another entity as part of its
lifecycle.
Example:
Code:
@Entity
public class Restaurant extends BaseEntity {
private String name;
private String address;
private String city;
private String description;
@OneToMany(mappedBy = "chosenRestaurant", cascade = [Link])
private List<FoodItem> foodItems = new ArrayList<>();
@Entity
public class FoodItem extends BaseEntity {
private String itemName;
private String itemDescription;
private boolean isVeg;
private int price;
@ManyToOne
@JoinColumn(name = "Restaurant_id", nullable = false)
private Restaurant chosenRestaurant;
}
Points to Remember:
Owning Side: The entity that contains the foreign key (e.g., FoodItem ).
Inverse Side: The entity that does not contain the foreign key (e.g., Restaurant ).
Uni-directional: The relationship is navigable only from one side (e.g., Course 1----->* Student ).
Bi-directional: Both sides of the relationship are navigable (e.g., Restaurant 1 <-----> * FoodItem ).
Bi-directional Setup:
2. Cascading in Hibernate
Cascading ensures that operations performed on one entity automatically propagate to its
associated entities. It simplifies managing the entity lifecycle.
Cascading Operations:
With cascade = [Link] , saving, updating, or deleting a Restaurant will automatically affect the
associated FoodItems .
3. Orphan Removal
You want a child entity to be automatically deleted when it is removed from the parent entity's
collection.
If you remove a FoodItem from the foodItems collection, it will be deleted from the database.
Use EAGER fetching for @OneToMany if you want to load the association immediately.
Alternatively, you can use JPQL with JOIN FETCH to fetch the related entities in a single query.
String jpql = "SELECT r FROM Restaurant r JOIN FETCH [Link] WHERE [Link] = :name";
List<Restaurant> restaurants = [Link](jpql, [Link])
.setParameter("name", "Pizza Hut")
.getResultList();
This will avoid lazy loading issues by fetching the associated foodItems with the Restaurant in one
query.
These methods encapsulate the logic for adding/removing child entities and ensure consistency in
the entity relationships.
Conclusion
By implementing inheritance, associations, cascading, and orphan removal in Hibernate, you can
manage complex entity relationships with minimal effort. Understanding the different fetching
strategies and how to handle lazy loading, along with defining helper methods for managing
collections, will make your entity management more robust and efficient.
Day 12
Hibernate Performance Tips:
Always configure the one side as the inverse side and the many side as the owning side
(FK containment).
4. One-to-One Associations:
Configure either uni or bi-directional based on your project’s data access needs.
5. Many-to-Many Associations:
Configure either uni or bi-directional based on your project’s data access needs.
2. Validation:
3. Comment Operations:
Post a new comment, including input like comment text, rating, commenter ID, and post ID.
4. Category Details:
5. One-to-One Association:
Configure a one-to-one relationship between User and Address , and manage cascading and
FK column names.
6. Many-to-Many Association:
Implement uni-directional many-to-many between Tags and Posts using @ManyToMany and
@JoinTable .
JPA Annotations:
1. @Transient: Marks a field to be excluded from persistence (not stored in the database).
In a One-to-Many or Many-to-One relationship, the owning side is the side that contains the
foreign key (FK) column and is responsible for maintaining the relationship in the database.
1. One-to-Many Relationship:
Owning side: The Many side (child) is the owning side because it contains the foreign key (FK)
reference to the parent entity.
Inverse side: The One side (parent) is the inverse side, which doesn't hold the foreign key.
Example:
@Entity
public class Category {
@OneToMany(mappedBy = "category") // inverse side
private List<Product> products;
}
@Entity
public class Product {
@ManyToOne // owning side
In this case, Product (many side) is the owning side because it has the foreign key category_id .
2. Many-to-One Relationship:
Owning side: The Many side (child) is the owning side because it contains the foreign key (FK)
reference to the parent entity.
Example:
@Entity
public class Order {
@ManyToOne // owning side
@JoinColumn(name = "customer_id") // FK column
private Customer customer;
}
@Entity
public class Customer {
@OneToMany(mappedBy = "customer") // inverse side
private List<Order> orders;
}
Here, Order (many side) is the owning side because it has the foreign key customer_id .
General Rule:
In a One-to-Many relationship, the Many side owns the relationship (contains the foreign key).
In a Many-to-One relationship, the Many side still owns the relationship because it holds the
foreign key.
2. The side with the @JoinColumn (which contains the foreign key) is the owning side.
Why It Matters:
The owning side is responsible for updating the relationship in the database (like
adding/removing associations).
The inverse side just reflects the association but doesn't directly modify the database
relationship.
Entity Types:
1. Definition: Entities have their own database identity, usually through a primary key.
2. Lifecycle: Entities have an independent lifecycle and can exist without any other entity.
3. Database Representation: Each entity instance is stored in its own row with a primary key.
4. Mandatory Annotations:
Example:
@Entity
public class College {
@Id
private Long id;
private String name;
}
Value Types:
1. Definition: Value types do not have their own identity (i.e., no primary key). They are defined
within an entity and do not exist independently.
3. Lifecycle: The lifespan of a value type is tied to the lifecycle of the owning entity.
4. Annotations:
Example:
@Embeddable
public class Address {
private String street;
private String city;
}
@Entity
public class User {
@Id
private Long id;
@Embedded
private Address address;
}
Example:
@Entity
public class User {
@Id
private Long id;
private String name;
private Integer age;
}
@Embeddable
public class Address {
@Entity
public class Student {
@Id
private Long id;
@Embedded
private Address address;
}
The collection must be stored in a separate table, with a join to the owning entity.
Collections of embeddable types and basic types are common use cases.
Example for Collection of Embeddable Types:
@Entity
public class User {
@Id
private Long id;
@ElementCollection
@CollectionTable(name = "CONTACT_ADDRESS", joinColumns = @JoinColumn(name =
"USER_ID"))
@AttributeOverride(name = "street", column = @Column(name = "STREET_ADDRESS"))
private List<Address> addresses;
}
@Entity
public class User {
@Id
private Long id;
@ElementCollection
@CollectionTable(name = "CONTACTS", joinColumns = @JoinColumn(name = "USER_I
D"))
@Column(name = "CONTACT_NO")
private Collection<String> contacts;
}
Example:
@Embedded
@AttributeOverride(name = "street", column = @Column(name = "STREET_ADDRESS"))
private Address address;
@Embeddable : Used to mark a class as a value type that can be embedded into other entities. The
class does not have its own identity and cannot exist independently.
Example:
@Embeddable
public class Address {
private String street;
private String city;
}
Summary:
Entities have their own primary key and lifecycle, marked by @Entity and @Id .
Value Types do not have their own primary key and are embedded in entities, marked by
@Embeddable and @Embedded .
LazyInitializationException in Hibernate
collection or an entity) is accessed outside the session scope, or when Hibernate tries to load an
associated entity or collection that was not fetched.
Hibernate uses lazy loading by default for one-to-many , many-to-many associations, meaning the
associated entities are not fetched immediately when the parent entity is loaded. Instead, they are
fetched only when accessed. However, if you try to access these associations after the session is
closed (i.e., the entity is detached), Hibernate cannot initialize them and throws the exception.
Here:
Problem:
If you load a Category entity and then access its posts collection after the session is closed,
Hibernate will throw a LazyInitializationException because the posts collection is represented by a proxy
that requires a database query to be loaded, but there is no open session to perform this query.
Disadvantages:
Not recommended: Eager loading can result in performance issues, especially with one-to-many
or many-to-many relationships. It forces Hibernate to load all associated entities even when they
are not needed, which can lead to performance bottlenecks.
Select N+1 Problem: If there are many BlogPost entries for each Category , Hibernate will execute
one query to load the categories and then separate queries to load each associated BlogPost ,
which is inefficient.
When to use: This solution is only suitable when the number of associated entities is small and you
need them immediately.
@Transactional
public Category getCategoryWithPosts(Long categoryId) {
Category category = [Link](categoryId); // Inside session
[Link]().size(); // Accessing the collection within the session
return category;
}
Disadvantages:
Hibernate fires multiple queries: One query for loading the category and then another query for
each associated BlogPost .
Less efficient than a single query that loads everything in one go, especially with large
collections.
String jpql = "select c from Category c join fetch [Link] where [Link] = :categoryName";
Category category = [Link](jpql, [Link])
.setParameter("categoryName", "Technology")
.getSingleResult();
Advantages:
Single query: Hibernate will use a single SQL JOIN to fetch the Category and its BlogPost entities,
avoiding the N+1 problem.
String jpql = "select c from Category c left join fetch [Link] where [Link] = :categoryName";
Category category = [Link](jpql, [Link])
.setParameter("categoryName", "Technology")
.getSingleResult();
This solution is efficient because it avoids multiple queries and still provides all the necessary data
in a single query.
Summary of Solutions:
2. Access the Collection Within the Session Scope: Ensures you access lazy-loaded collections
while the session is open, but may result in multiple queries being fired.
3. Use JOIN FETCH in JPQL: Most recommended solution to fetch associations in a single query
without LazyInitializationException or N+1 select issues.
Day 13
Why Spring?
Spring simplifies Java development and promotes best practices like loose coupling and easy
testability. Here's why you would use it:
2. Loose Coupling: Using Dependency Injection (DI) and Inversion of Control (IoC), Spring
enables the decoupling of components and their dependencies.
3. Design Patterns Support: Spring offers implementations of common design patterns like
Singleton, Factory, Proxy, and MVC.
4. Reduces Boilerplate Code: Spring eliminates repetitive code (like managing connections,
handling transactions, etc.), improving maintainability.
5. Lightweight: Spring applications are light and easily configurable, especially when compared to
heavyweight frameworks.
6. Excellent Database Integration: Supports JDBC and ORM (Hibernate) for seamless database
interaction with transaction management.
7. Modular Design: Spring's modular architecture allows you to pick and choose only the
necessary modules.
8. Integration with Other Frameworks: Easily integrates with other technologies like Hibernate,
Struts, and EJB.
10. Testing Support: Built-in support for unit testing and integration testing using frameworks like
JUnit and Mockito.
12. Secure Web Development: Provides built-in tools to secure web apps and RESTful web
services.
What is Spring?
1. Spring is a Container: It manages the lifecycle of beans, which are just plain Java objects
(POJOs) that Spring can manage.
2. Framework of Frameworks: Spring provides various modules that can be used together or
separately. These modules include frameworks like Spring MVC, Spring Boot, Spring Data,
Spring Security, etc.
3. Modular and Extensible: Spring is a highly modular framework, allowing developers to include
only the necessary components.
DI allows for loose coupling. Objects don’t create their dependencies, but rather receive
them from the container. This makes code easier to test and maintain.
5. Spring Framework's Design Patterns: It offers implementations of various design patterns like
Singleton, Factory, Proxy, Front Controller, MVC, and Template Method.
Traditional Java code often tightly couples dependent objects and their dependencies (e.g.,
DAOs, utilities). Changing one dependency requires changes in all dependent objects,
making maintenance harder.
2. What is DI?
Spring uses Inversion of Control (IoC) to manage the creation and injection of
dependencies.
IoC: The container, not the dependent object, controls the lifecycle and injection of
dependencies.
Example:
@Autowired
private IUserService userService;
The @Autowired annotation allows Spring to inject the IUserService implementation into the
UserController without manually instantiating it.
2. Dependency Injection: Spring injects dependencies into the bean (via constructor or setter
injection).
3. Post-Processing: After the bean is initialized but before it is used, bean post-processors may
modify the bean.
Client (Browser)
|
v
Servlet / JSP
|
v
Service Layer (Java Beans, Business Logic)
|
v
JDBC / Hibernate DAO
|
v
Client (Browser)
|
v
DispatcherServlet (Front Controller)
|
v
Controller / RestController
|
v
Service Layer (Business Logic, Transaction)
|
v
Repository Layer (DAO Layer - Interface/Impl)
|
v
Entity / Value Object (POJO)
|
v
Database
Key Differences:
Feature Before Spring After Spring MVC
Business Logic Layer Java Beans manually linked @Service with DI (Spring-managed)
Bean Wiring
Spring allows you to wire dependencies in two ways:
Setter-based DI:
Constructor-based DI:
@Autowired
private IUserService userService;
ApplicationContext: Extends BeanFactory and provides more advanced features like event
handling and internationalization.
2. Prototype: A new instance of the bean is created each time it’s requested.
Spring provides multiple ways to configure beans: XML-based, Annotation-based, and Java-
based configuration.
AOP (Aspect-Oriented Programming) allows the separation of concerns like logging, security,
and transaction management.
Spring enables building loosely-coupled, modular applications with various scopes (singleton,
prototype, etc.), simplifying the development of web applications and microservices.
By following the Spring approach, you ensure that your application is easy to maintain, extend, and
test.
Controller Layer (e.g., Service Layer (e.g., To handle business logic requested by web
UserController ) IUserService ) layer or REST clients.
DAO Layer (e.g., ORM/JDBC Tools (e.g., To establish DB connection and execute
UserDaoImpl ) SessionFactory , JdbcTemplate ) queries.
@RestController
public class UserController {
@Autowired
private IUserService userService; // dependent on IUserService for business logic
}
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao; // dependent on DAO for DB operations
}
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private SessionFactory sessionFactory; // dependency for getting DB session
}
✅ Final Summary
Controllers depend on Services to perform business logic.
All of these objects rely on Spring Container to inject their dependencies (via Dependency
Injection).
Hibernate/JDBC
getCurrentSession() , Executes SQL/JPQL to
DAO ( SessionFactory ,
executeUpdate() , query() interact with database
JdbcTemplate )
Injects dependencies
All Beans (Controller,
Spring Container constructor/setter automatically (via DI) at
Service, DAO)
runtime
2. [Link]() is called
➤ Calls [Link](user)
3. [Link]() is called
4. [Link]() is called
➤ Calls [Link]().save(user)
Controller
registerUser() HTTP Client To trigger a registration
( UserController )
⚙️ Summary
The flow is: Client → Controller → Service → DAO → DB
Each layer delegates the job down to keep logic separated and maintain loose coupling.
Spring Container is responsible for calling the constructor or setter methods to wire
dependencies automatically (that’s IoC/DI).
Day 14
🔷 Model 1 Architecture
✅ Technologies Used:
Servlets and JSP
⚙️ How it Works:
Client request is directly handled by JSP or Servlet.
✅ Advantages:
Simple and quick to develop.
❌ Disadvantages:
Poor separation of concerns — mixing of HTML (presentation) with Java code (logic).
⚙️ How it Works:
Client sends request → handled by a Controller (Servlet).
📌 MVC Breakdown:
Component Role Example
✅ Advantages:
Centralized control — only controller decides page flow.
❌ Disadvantages:
Advance java Day Wise - Akshay 90
Initial development is more complex.
Handler Mapping
View Resolver
✅ Summary Table:
Feature Model 1 Model 2 (MVC)
Web Client
↓
Front Controller (Servlet)
↓
→ Forwards to appropriate Servlet for business logic
OR
→ JSP for response generation (View)
↓
Services → JavaBeans → DAO Layer → POJOs → DB
🔁 MVC Components:
Role Responsibility
✅ Advantages:
Centralized control
@Autowired
private Teacher myTeacher;
Exception scenarios:
No match → NoSuchBeanDefinitionException
Using @Autowired(required=false) :
Avoids exception if bean not found, but may cause NullPointerException if used without null
check
DispatcherServlet:
4. ModelAndView Usage
${[Link]}
Annotations:
2. Scope Attribute
XML:
Annotation:
@Scope("singleton") , etc.
3. Lazy Initialization
XML:
Annotation:
4. Init Method
XML:
Annotation:
@PostConstruct on method
5. Destroy Method
XML:
Annotation:
@PreDestroy on method
<context:component-scan> @ComponentScan
✅ Conclusion:
XML Configuration is declarative and externalized.
MVC-2 Architecture
1. Request processing
2. Creating JavaBeans
6. Forwarding the request to appropriate View Layer (like JSP) using [Link]() .
🧠 3. Model (JavaBeans)
Contains:
✅ Summary Table
Component Responsibility Example
✅ MVC Advantages
1. Separation of Concerns
Division of responsibilities among various components: Model (data), View (UI), and Controller
(logic).
2. Balanced Responsibility
3. Cleaner Architecture
Better separation between:
Request processing
Navigation
Business logic
Presentation logic
4. Reusability
5. Independent Development
A single model can support multiple views, and the controller can dynamically decide which
view to render based on logic.
🔹 Purpose:
To pass business logic results from the backend (Controller) to the frontend (View).
Helps populate UI elements like tables, forms, dropdowns using server-side data.
3. If present:
It stores them under the request scope
${[Link]}
or
${attrName} // since requestScope is default in JSP
@GetMapping("/home")
public ModelAndView showHome() {
Student student = new Student("Akshay", 23);
return new ModelAndView("home", "student", student);
}
@GetMapping("/home")
public String showHome(Model model) {
[Link]("student", new Student("Akshay", 23));
return "home"; // LVN
}
@GetMapping("/home")
public String showHome(ModelMap map) {
[Link]("student", new Student("Akshay", 23));
return "home";
}
@PostMapping("/register")
public String registerStudent(@ModelAttribute Student student) {
// Spring binds form fields to Student object
return "success";
}
[Link]("name", "Akshay");
<p>Hello, ${name}</p>
${[Link]}
If the date format doesn't match Spring's default ( MM/dd/yyyy ), fix it using:
return "redirect:/home";
Internals:
Spring calls:
[Link](...)
Add via:
${[Link]}
Acts as the central entry point for all requests in Spring MVC (MVC Model 2 pattern).
Receives incoming requests and delegates them to appropriate components for processing.
3. Handler Mapping
The selected controller method executes business logic based on request data
(parameters, path variables, etc.).
Model holds the data to display; view name indicates which template should be used.
6. View Resolution
DispatcherServlet consults the configured View Resolver to map the logical view name to
the actual view implementation (e.g., JSP, Thymeleaf).
7. View Rendering
The view engine (e.g., Thymeleaf, JSP) merges the model data with the template to
generate the final HTML or other content.
8. Response Sent
DispatcherServlet sends the rendered response back to the client over the network.
Additional Notes:
Interceptors can intercept requests/responses before and after controller execution.
Spring MVC offers rich features like flexible request mapping, data binding, form validation, and
more.
2. Front Controller ( DispatcherServlet ): Acts as a central controller, configured via [Link] , receiving
all incoming requests.
3. Handler Mapping: Determines which controller should handle the request based on defined
mappings.
5. Service Layer: Contains business logic, coordinating data retrieval and manipulation.
9. View Resolver: Determines the correct view (JSP file) to render the response.
10. View Layer (JSP): Generates the final response presented to the client.
4. Database Configuration: Properties file defines database credentials and connection settings.
6. Spring Layers:
DAO Layer: Handles database interactions, reduces boilerplate code ( @Repository , @Autowired
SessionFactory).
This setup allows developers to leverage Spring’s MVC architecture with Hibernate for efficient
database interactions without the need for Spring Boot.
2. Front Controller ( DispatcherServlet ): Acts as the entry point, directing requests to the appropriate
handler.
3. Handler Mapping: Determines which controller method will handle the request.
4. Controller ( @Controller , @RequestMapping ): Processes the request, invoking the service layer.
5. Service Layer ( @Service ): Contains business logic, ensuring smooth application operations.
10. Response Generation: The final processed data is sent back to the client as an HTTP response.
This structure ensures a modular, scalable, and maintainable web application by separating
concerns effectively.
You import your Hibernate configuration XML ( [Link] ) inside your Spring config.
Starts the Servlet Context (SC) using the configured XML (usually named after servlet:
[Link] ).
SC scans base packages (via component-scan) and creates bean instances of Controllers,
Services, DAOs, applying lifecycle management (singleton by default).
The app is now ready to handle HTTP requests routed through DispatcherServlet → Controller
→ Service → DAO → DB.
Properties: JDBC driver, URL, username, password, connection pool initial and max sizes.
LocalSessionFactoryBean
Injects DataSource.
Depends on SessionFactory .
Generates a URL relative to the current context path, helps avoid hardcoding context root.
Spring Boot is introduced to solve this by providing auto-configuration, reducing XML to near
zero.
Refer to your mentioned readmes for detailed steps and reasoning behind Spring Boot's
inception.
You can move from XML configs to Java-based config or [Link] / [Link] .
Reason:
Spring Boot uses JPA ( EntityManager ) as abstraction over native Hibernate APIs.
EntityManager is thread-safe and integrates well with Spring Boot transaction management.
Supports:
Pagination, sorting.
Summary
Legacy Spring MVC + Lots of XML config, manual session and transaction management, native
Hibernate Hibernate APIs
Spring Data JPA Ready-made CRUD repo implementations, less boilerplate DAO code
Steps and code snippets for porting to Spring Boot + Spring Data JPA.
Defines interfaces such as EntityManager , EntityTransaction , and annotations like @Entity , @Id ,
@OneToMany , etc.
Main purpose:
Letting you define repositories as interfaces only — no need for DAO implementation classes.
PagingAndSortingRepository<T,
Adds pagination and sorting findAll(Sort) , findAll(Pageable)
ID>
2. Usage Example
You just declare the interface extending JpaRepository , and Spring Data will auto-generate the
implementation.
Iterable<T> findAll()
Spring Data parses the method name, generates the corresponding JPQL query automatically.
Supports:
@Modifying
@Query("update User u set [Link] = ?1 where [Link] = ?2")
int setFixedFirstnameFor(String firstname, String lastname);
C) Transaction Management
By default, Spring Data JPA uses @Transactional internally to manage transactions for repository
methods.
You can override transactional behavior per method or repository by using @Transactional
annotations manually.
D) Exception Translation
Spring Data repositories have the @Repository stereotype applied internally.
Inject repositories into services and call CRUD or custom methods directly.
Remove all manual DAO implementations if migrating from native Hibernate DAO.
Day 16
It's a business functionality (like banking, customer service, payment gateways, stock
exchange info) exposed to remote clients over a standard protocol (mostly HTTP/HTTPS).
Core idea: Enable remote access to business logic via the internet.
Roles:
Now replaced by JAX-WS (Java API for XML Web Services), using SOAP.
Spring offers Spring Web Services and Spring MVC REST support with less boilerplate and
easier integration.
Summary Table
Technology Description Protocol Data Format Ease of Setup Interoperability
Java-specific
Java RMI Java RMI Java Object Moderate Java-only
remote calls
Cross-language
CORBA IIOP Binary/XML Complex Cross-platform
remote calls
Simplified
Spring Web SOAP/HTTP or
SOAP/REST on XML/JSON Easy High
Services HTTP
Spring
What is REST?
REST = REpresentational State Transfer
REST is all about transferring representations of resources between client and server.
Representation:
The state or data of a resource, transferred as JSON, XML, HTML, or plain text. JSON is the
most common and lightweight format today.
Client:
The consumer or accessor of resources.
Server:
The provider of resources.
RESTful Architecture
Resource-Oriented Architecture (ROA) — REST revolves around resources, with a uniform
interface to manipulate them.
Used widely in business applications, e.g., payment gateways, weather data, social media, etc.
Example:
1. Uniform Interface:
Simplifies and decouples the architecture by having a standard way to interact with resources.
2. Stateless:
Each request from client to server must contain all information needed to understand and
process it (no client context stored on server).
3. Cacheable:
Responses must explicitly define themselves as cacheable or not to improve performance.
4. Client-Server:
5. Layered System:
Architecture can have multiple layers for scalability (e.g., load balancers, proxies).
Clients request, servers respond without impacting each other’s internal workings.
Enables different clients (mobile, web, IoT) to interact with the same server.
2. Statelessness
Every request from client to server must contain all information needed to understand and
process it.
3. Uniform Interface
Standardized way for client-server communication.
4. Layered System
API architecture is divided into hierarchical layers.
5. Cacheability
Responses explicitly indicate whether they are cacheable.
A request is considered same origin if all three of these match between the requesting page
(client) and the resource being requested (server):
Example:
Cross Origin:
If any one of domain, protocol, or port differs, the request is considered cross origin.
Example:
2. The cross-origin server receives this request and decides whether it allows access from that
origin.
Otherwise, the browser blocks the response, and a CORS error appears in the console.
Origin header tells the server the origin of the webpage making the request
( [Link] ).
HTTP/1.1 200 OK
Access-Control-Allow-Origin: [Link]
Content-Type: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Summary
Step Browser Request Header Server Response Header Effect
What is ResponseEntity ?
ResponseEntity<T> is a generic class in Spring Framework that represents the entire HTTP
response —
[Link]([Link]).body(bodyObject);
@GetMapping("/employee/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
Employee emp = [Link](id);
if (emp == null) {
// Return 404 NOT FOUND with empty body
return [Link](HttpStatus.NOT_FOUND).body(null);
}
// Return 200 OK with employee data
return [Link]([Link]).body(emp);
}
Day 17