Different Hibernate object states and their lifecycle in Hibernate | Techartifact

There are 3 hibernate object state

1.) Persistent– Persistent object and collections are short lived single threaded objects, which store the persistence state. These objects synchronize their state with database depending on your flush strategy(i.e auto flush where as soon as setXXX() method is called or an item is removed from a set,list etc or define your own synchronization points with session.flush().transaction.commit() calls.) If you remove an item from persistence collections like a Set, it will be removed from database either immediately or when flush() or commit() is called depending on your flush strategy. They are plain old java objects(POJO) and are currently associated with session. As soon as the associated session is closed , persistence objects become detached objects and are free to use directly as data transfer objects in any application layer like business Layers, presentation layer etc.

2.) Detached – These objects and collection are instances of persistence objects that were associated with a session but currently not with associated with session. These objects can be freely used as Data Transfer Objects without having any impact on your database .Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc and become persistence objects.

3.) Transient – These objects and collection are instance of persistence object that were never associated with session.These objects can be freely used as Data transfer objects without having any impact on your database. Transient objects become persistent objects when associated to session by calling session.save(), session.persist() etc.

4.) Removed State -A previously persistent object that is deleted from the database session.delete(account).Java instance may still exist, but it is ignored by Hibernate -Any changes made to the object are not saved to the database Picked up for garbage collection once it falls out
of scope
• Hibernate does not null-out the in-memory object

JSP Life cycle

Life cycle of a JSP page consists of two phases, translation phase and execution phase. Every JSP is a Servlet, a JSP page is translated and compiled into servlet and the resulting servlet handles the request, So life cycle of a JSP page largely depends on the Servlet API.

JSP engine does the following 7 phases.

• Page translation: page is parsed, and a java file which is a servlet is created.
• Page compilation: page is compiled into a class file
• Page loading : This class file is loaded.
• Create an instance : Instance of servlet is created
• jspInit() method is called
• jspService is called to handle service calls
• jspDestroy is called to destroy it when the servlet is not required.

Translation phase

During the translation phase, JSP page is translated into a servlet class. The entire static markup in the JSP page is converted into the code that writes the data to response stream. If you look at the source of the generated Servlet class you will find calls to the out.write() which write data to ServletOutputStream.

If you have following HTML code into your JSP page
JSP life cycle tutorial
It will generate code like
out.write(“JSP life cycle tutorial”)

During the translation phase JSP elements are treated as follows:
• JSP directives controls the behavior of the resultant servlet.
• Scripting elements results into the equivalent Java code.
• Custom tags are converted into the code that calls method on tag handlers.

JSP Page Compilation:

The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.


Class Loading:

The java servlet class that was compiled from the JSP source is loaded into the container

Execution phase

JSP life cycle’s execution phase is almost similar to that of the Servlet life cycle, because ultimately it’s a servlet which is being executed. The Servlet class generated at the end of the translation phase represents the contract between container and the JSP page. According to the JSP specification the servlet class must implement the HttpJspPage interface which defines the life cycle methods.
JSP life cycle includes three methods jspInit(), _jspService() and jspDestroy()

Initialization:

jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.
_jspService() execution:
This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.
jspDestroy() execution:
This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

The HttpJspPage Interface

The javax.servlet.jsp.HttpJspPage contains three methods

Public void jspInit()

This method is invoked when the JSP page is initialized. This method is similar to init() method in servlet. If you want to provide initialization for a JSP page, you define this method in declaration part of the JSP page. But most of the time you will not need to define this method.

public void _jspService
void _jspService(HttpServletRequest request, HttpServletResponse response)ThrowsIOException, ServletException
This method represents the body of the JSP page and invoked at each client request. This method is similar to service() method in servlet.
Note: You should never provide implementation _jspService() method as web container automatically generates this method based on the content of the JSP page

Public void jspDestroy()

This method is invoked just before the JSP page is destroyed by the web container. This method is similar to destroy() method in servlet. If you want to provide some cleanup code, you can define this method in declaration part of the JSP page.

Understanding the Servlet life cycle with an example

This example explains how to execute code at JSP initialization phase and destroy phase of JSP Life Cycle.
It is a simple request counter that displays how many time the page has been called or how many requests the page has received. The page declares a counter variable of type integer, the counter is set to zero when the page is initialized. Each time the page receives a request, the value of counter variable is incremented by one and displayed to user. During each life cycle stage, A message is logged to server log.
lifecycle.jsp

	<%! 
	int counter;
	public void jspInit() {
		counter = 0;
		log("The lifecycle jsp has been initialized");
	}		
	%>	
 
<html>
	<head>
		<title>JSP Life Cycle Example</title>	
	</head>
	<body>
		<%
		log("The lifecycle jsp has received a request");
		counter++;
		%>		
		<h2>JSP Life cycle : Request counter</h2>
		<p>This page has been called <%=counter %> times </p>
	</body>
</html>
	<%!
		public void jspDestroy() {
		log("The lifecycle jsp is being destroyed");
	}
	%>

Pin it

Servlet lifecycle

Servlets are managed by web container.Life cycle defines how servlet is loaded, instantiated and initialized, handles requests from clients and how it is taken out of service.The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes.
The servlet life cycle methods defined in Servlet interface are init(), service() and destroy().
The signature of these methods are shown below.

public void init(ServletConfig config) throws ServletException

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

public void destroy()

First the url collected from the user generates an http request, this request is mapped with the appropriate servlet and loaded in the address space of the server. once the servlet is loaded the following 3 phases starts
Init() – initializes the servlets initialization information with the configuration parameters.
Service – business logic i.e. request and response services goes here.
Destroy() – used to destroy all variables and objects used by the servlet.
Loading and instantiation during this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request.

Initialization
The web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application Request handling After a servlet is properly initialized, the servlet container may use it to handle client requests. Requests are represented by request objects of type ServletRequest. The servlet fills out response to requests by calling methods of a provided object of type ServletResponse. These objects are passed as parameters to the service method of the Servlet interface. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.
End of service

When servlet container determines that the servlet should be removed from the service, it calls the destroy() method of the servlet to allow servlet to release any resources it is using (eg. database connections or file handles). Before calling the destroy() method, the container allows any request threads that are currently running in the service method to complete execution within a defined time limit. Once the servlet is removed out of service, container will not send any requests to the servlet. If the servlet needs to be put in service again, the container will create a new servlet instance and the life cycle begins from the initialization phase.

Understanding the Servlet life cycle with an example

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class ServletLifeCycleExample extends HttpServlet {
 
	private int count;
 
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		getServletContext().log("init() called");
		count=0;
	}
 
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		getServletContext().log("service() called");
		count++;
		response.getWriter().write("Incrementig the count: Count = "+count);
 
	}
 
	@Override
	public void destroy() {
		getServletContext().log("destroy() called");
	}	

Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.

First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.

Pin it