Advance Java by Madhura Anturkar
Advance Java by Madhura Anturkar
Advance Java by Madhura Anturkar
Madhura Anturkar
Version Java EE 8 (J2EE 1.8) maintained under Oracle / Jakarta EE 8 (maintained by
eclipse foundation)
1. What is J2EE ?
An enterprise application (EA) is a large software system platform designed to operate in a corporate environment .
It includes online shopping and payment processing, interactive product catalogs, computerized billing systems,
security, content management, IT service management, business intelligence, human resource management,
manufacturing, process automation, enterprise resource planning ....
Servlet API,JSP(Java server page) API,Security,Connection pooling ,EJB (Enterprise Java Bean), JNDI(Naming service --
Java naming & directory i/f),JPA(java persistence API),JMS(java messaging service),Java Mail, Java Server Faces , Java
Transaction API, Webservices support(SOAP/REST) etc...
J2EE complaint application server --- web container + EJB (enterprise java bean) container
IBM -- Websphere
2. WHY J2EE
2. J2EE server independence --- Create & deploy server side appln --on ANY J2ee compliant server --- guaranteed to
produce SAME results w/o touching or re-deploying on ANY other J2EE server
3. Ready made implementation of primary services(eg --- security, conn,pooling,email....)--- so that J2EE developer
DOESn't have to worry about primary services ---rather can concentrate on actual business logic.
1|Page
3. Layers involved in HTTP request-response flow (refer to day1-data\day1_help\diags\request-response-flow.png)
eg : http://www.abc.com:8080/day1.1
4. What is dyn web application --- server side appln --deployed on web server --- meant for servicing typically web
clnts(thin) -- using application layer protocol HTTP /HTTPS
Read --HTTP basics including request & response structure from day1-data\day1_help\j2ee_prerequisites\HTTP
Basics
5. Objective ?: Creating & deploying dyn web appln on Tomcat -- For HTML content
Its details -- Refer to diag (J2EE compliant web app folder structure)
Jobs ---
created by -- dev
who reads it -- WC
what --- dep instrs --- welcome page, servlet deployment tags, sess config, sec config......
What is a servlet ?
-- Java class (with NO main method) -- represents dynamic web comp - whose life cycle will be managed by WC(web
container : server side JVM)
no main method
Job list
1. Request processing
2|Page
2. B.L
5. Page navigation
1. Via annotation
eg : @WebServlet(value="/validate")
Map :
key -- /validate
URL : http://host:port/day1.1/validate?....
web.xml
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>pages.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
WC : map
key : /test2
value : pages.SecondServlet
eg URL --http://host:port/day1_web/hello
At the time of web app deployment ---WC tries to populate map of url patterns , from XML tags (from web.xml).
Later ---it will check for @WebServlet annotation
Objective 2: Test basic servlet life cycle -- init , service ,destroy (deployed via xml)
3|Page
javax.servlet.ServletRequest i/f methods
Objective 3 : Accept different type of i/ps from user , in HTML form.Write a servlet to display request parameters.
==================================================================================
Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality
?
It is abstract because the implementations of key servicing methods have to be provided by (e.g. overridden by)
servlet developer. Since it's abstract , it's instance can't be created.
A subclass of HttpServlet must override at least one method, usually one of these:
init and destroy, to manage resources that are held for the life of the servlet
If you extend the class without overriding any methods, you will get a useless servlet; i.e. it will give an error
response for all requests.(HTTP 405 : Method not implemented) . So , if the class was not abstract, then any direct
instance of HttpServlet would be useless.
So the reason for making the HttpServlet class abstract is to prevent a programming error.
As a servlet developer , you can choose to override the functionality of your requirement (eg : doPost)
==================================================================================
2 Ways
1. Client Pull
1.1 User takes some action --eg : clicking on a button or link & then client browser generates new URL to take user to
the next page.
User doesn't take any action. Client browser automatically generates new URL to take user to the next page.(next
page can be from same web appln , or diff web appln on same server or any web page on any srvr)
API of HttpServletResponse
response.sendRedirect("s2");
4|Page
2. Server Pull.
Client sends the request to the servlet / JSP. Same request can be chained to the next page for further servicing of
the request.
Steps
1. Create Request Dispatcher object for wrapping the next page(resource --can be static or dynamic)
API of ServletRequest
2.Forward scenario
API of RequestDispatcher
This method allows one servlet to do initial processing of a request and another resource to generate the response.
(i.e division of responsibility)
Uncommitted output in the response buffer is automatically cleared before the forward.
If the response already has been committed(pw flushed or closed) , this method throws an IllegalStateException.
Limitation --only last page in the chain can generate dynamic response.
3. Include scenario
API of RequestDispatcher
Includes the content of a resource @run time (servlet, JSP page, HTML file) in the response. -- server-side includes.
Limitation -- The included servlet/JSP cannot change the response status code or set headers; any attempt to make a
change is ignored.
==========================================================================================
What is a Session?
Session is a conversional state between client and server and it can consists of multiple request and response
between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when
some unique information about the session is passed between server and client in every request and response.
HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to
process and they cant identify if its coming from client that has been sending request previously.
But sometimes in web applications, we should know who the client is and process the request accordingly. For
example, a shopping cart application should know who is sending the request to add an item and in which cart the
item has to be added or who is sending checkout request so that it can charge the amount to correct client.
Consists of all requests/resps coming from/ sent to SAME clnt from login to logout or till session expiration tmout.
2. HttpSession interface
----------------------------------------------
Techniques
What is a cookie?
Created by -- server (servlet or JSP prog or WC) & downloaded (sent) to clnt browser---within response header
Cookie represents data shared across multiple dyn pages from the SAME web appln.(meant for the same client)
Steps :
HttpServletResponse API :
void addCookie(Cookie c)
HttpServletRequest :
Cookie[] getCookies()
String getName()
String getValue()
int getMaxAge()
6|Page
0. Web developer (servlet prog) has to manage cookies.
1. Cookies can handle only text data : storing Java obj or bin data difficult.
3. In cookie based approach : entire state of the clnt is saved on the clnt side. If the clnt browser rejects the cookies:
state will be lost : session tracking fails.
How to redirect client automatically to next page ? (in the NEXT request)
API of HttpServletResponse
eg : resp.sendRedirect("s2");
IMPORTANT :
WC -- throws
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed(eg :
pw.flush(),pw.close()...)
In this technique :
Entire state of the client is not saved on client side , instead saved on the server side data structure (Http Sesion
object) BUT the key to this Http Session object is STILL sent to client in form of a cookie.(cookie management is done
by WC)
Servlet programmer can store/restore java objects directly under the session scope(API : setAttribute/getAttribute)
HttpSession getSession()
Meaning --- Servlet requests WC to either create n return a NEW HttpSession object(for new clnt) or ret the existing
one from WC's heap for existing client.
OR
equivalent to map.put(k,v)
eg : hs.setAttribute("cart",l1);
4. To get session ID (value of the cookie whose name is jsessionid -- unique per client)
String getId()
HttpSession API
(WC marks HS object on the server side for GC ---BUT cookie is NOT deleted from clnt browser)
6. HttpSession API
Rets true for new client & false for existing client.
<session-config>
<session-timeout>5</session-timeout>
</session-config>
NOTE :
What is an attribute ?
who creates server side attrs ? -- web developer (servlet or JSP prog)
Each attribute has --- attr name(String) & attr value (java.lang.Object)
Attributes can exist in one of 3 scopes --- req. scope,session scope or application scope
8|Page
1. Meaning of req scoped attr = attribute is visible for current req.
2. Meaning of session scoped attr = attribute is visible for current session.(shared across multiple reqs coming from
SAME clnt)
3. Meaning of application scoped attr = attribute is visible for current web appln.(shared across multiple reqs from
ANY clnt BUT for the SAME web application)
==============================================================================================
Web container(WC)
3. When ?
After WC creates servlet instance(via def constr), ServletConfig instance is created & then it invokes init() method of
the servlet.
4. Usage
(i.e the init-param is accessible to one servlet only or you can say that the init-param data is private for a particular
servlet.)
XML Tags
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>ex.TestInitParam</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>
===============================================================================================
NOTE : The ServletContext object is contained within the ServletConfig object, which the WC provides the servlet
when the servlet is initialized.
5. Usages
In web.xml
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
1. Get ServletContext
API of GenericServlet
2. ServletContext API
10 | P a g e
String getInitparameter(String paramName) : rets the param value.
H.W
===============================================================================================
The Servlet API provides a number of listener interfaces that one can implement in order to react to these events.
1. ServletRequestListener
2. HttpSessionListener
3. ServletContextListener
Steps
2. Register it with WC
OR
<listener>
</listener>
==============================================================================================
Dynamic web component , whose life-cycle is managed by WC(JSP container/Servlet container/Servlet engine)
WHY JSP?
1. JSP allows developer to separate presentation logic(dyn resp generation) from Business logic or data
manipulation logic.
11 | P a g e
Typically JSPs -- used for P.L(presentation logic)
2. Ease of development --- JSP pages are auto. translated by W.C in to servlet & compiled & deployed.
3. Can use web design tools -- for faster development (RAD --rapid application development) tools.
JSP API
Never override _jspService ---JSP container auto translates JSP tags (body) into _jspService.
JSP life-cycle
5. Request processing phase / Run time phase. : typically handled by the Servlet Container.
7. The 1st it calls : public void jspInit() : one time inits can be performed.(jspInit availble from
javax.servlet.jsp.JspPage)
8. Then it will call follwing method using thrd created per clnt request :
12 | P a g e
When _jspService rets , thread's run method is over & thrd rets to the pool, where it can be used for servicing some
other or same clnt's req.
9.. At the end ...(server shutting down or re-deployment of the context) : the S.C calls
1. JSP comments
significance : JSP translator & compiler does not ignore the commented text BUT clnt browser will ignore it.
2.1 out - javax.servlet.jsp.JspWriter : represents the buffered writer stream connected to the clnt via
HttpServletResponse(similar to your PW in servlets)
2.4 session : HttpSession (By def. all JSPs participate in session tracking i.e session obj is created)
2.6 pageContext : current page environment : javax.servlet.jsp.PageContext(this class stores references to page
specific objects viz -- exception,out,config,session)
2.7 application : ServletContext(used for Request dispatching, server side logging, for creating context listeners,to
avail context params, to add/get context scoped attrs)
2.8 page --- current translated page class instance created for 'this' JSP
3. Scripting elements : To include the java content within JSP : to make it dynamic.
3.1 Scriptlets : can add the java code directly . AVOID scriptlets . (till Javabeans & custom tags or JSTL, we will use
use the scriptlets to add : Req. processing logic, B.L & P.L)
usage : till Java beans or cust. tags are introduced : scriptlets used for control flow/B.L/req. proc. logic
significance : the expr gets evaluated---> to string -> automatically sent to clnt browser.
Better alternative to JSP Expressions : EL syntax (Expression Lang. : avlble from JSP 1.2 onwards)
JSP implicit object --- request,response,session....---accessible from scriptlets & JSP exprs. ---
14 | P a g e
${abc} ---
null
null
session.getAttribute("abc") ---
null
eg : ${sessionScope.nm}
${pageContext.session.id}
${pageContext.request.contextPath} ---/day5_web
${pageContext.session.maxInactiveInterval}
----
${param}
{user_nm=asdf, user_pass=123456}
Usage : 1. for creating page scoped java variables & methods (instance vars & methods/static members)
location inside the translated page : outside of _jspService (directly within JSP's translated class)
------------------------
JSP Directives --- commands/messages for JSP Engine(=JSP container=WC) -- to be used @Translation time.
15 | P a g e
Syntax ---
1. page directive
Syntax
If u enable this to true--- one can access 'exception' implicit object from this page.
This exception obj is stored under current page ---i.e under pageContext (type=javax.servlet.jsp.PageContext -- class
which represents curnt JSP)
${pageContext.exception.message}
-- evals to pageContext.getException().getMessage()
Additional EL syntax
Throwable : ${pageContext.errorData.throwable}<br/>
true=>informing WC--- JSP is already written in thrd -safe manner ---- DONT apply thrd safety.
(NOT recommended) ---WC typically marks entire service(servlet scenario) or _jspService in JSP scenarion ---
synchronized. --- this removes concurrent handling of multiple client request --so not recommended.
What is reco? --- isThreadSafe=true(def.) --- identify critical code--wrap it in synchronized block.
16 | P a g e
eg ---Context scoped attrs are inherently thrd -un safe. So access them always from within synched block.
Servlet class can imple. tag i/f -- javax.servlet.SingleThreadModel(DEPRECATED) -- WC ensures only 1thread
(representing clnt request) can invoke service method. --NOT NOT recommended.
2. include directive
Via include directive ---- contents are included @ Translation time.--- indicates page scope(continuation of the same
page).
Typically used -- for including static content (can be used to include dyn conts)
eg ---one.jsp
two.jsp.....
-----------------------
</jsp:actionName>
---1. allows prog to seperate B.L in JBs.(Req processing logic, Page navigation & resp generation will be still part of
JSP)
JBs can store conversational state of clnt(JB 's properties will reflect clnt state) + supplies Business logic methods.
3. Auto. translation between req. params & JB props(string--->primitive data types auto. done by WC)
What is JB?
3. Properties of JBs --- private, non-static , non-transient Data members --- equivalent to request params sent by
clnt.(Prop names MUST match with req params for easy usage)
In proper words --- Java bean props reflect the conversational state of the clnt.
4. per property -- if RW
naming conventions of JB
17 | P a g e
public void setPropertyName(Type val)
{...}
----------------------------
JB = server side obj (attribute), attr name --- bean id,attr val -- bean inst.,can be added to any scope using scope
atribute.
eg :
eg --- beans.Userbean
setters/getters
Usage ---
---loc/load/inst JB class
18 | P a g e
2. JSP using JB action
Usage--
value="a@b"/>
OR via EL
value="${param.f1}"/>
WC invokes ---
session.getAttribute("user").setEmail(request.getParameter("f1"));
2.2
Usage eg --
WC invokes ---
((Userbean)request.getAttribute("user")).setEmail(request.getParameter("f1"));
2.3
usage
eg -- If rq. param names are email & password(i.e matching with JB prop names) then ---matching setters(2) will get
called
Usage --
WC ---
${sessionScope.user.email} ---
${requestScope.user.validUser.email}
19 | P a g e
request.getAttribute("user").getValidUser().getEmail()
${pageContext.exception.message}
eg : In one.jsp
<jsp:forward page="two.jsp"/>
rd.forward(request,response);
w/o writing scriptlets --- use additional std actions --- supplied as JSTL actions
1. jstl-1.2.jar
1.Copy above JAR into ur run-time classpath(copy jars either in <tomcat_home>/lib OR <web-inf>/lib
2. Use taglib directive to include JSTL tag library into ur JSP pages.
tag=action
supplier = JSTL vendor(spec vendor=Sun, JAR vendor=Sun/any J2EE compliant web/app server)
Tag libr- TLD -- Tag library descriptor -- desc of tags -- how to use tags
3.1 eg
---WC
pageContext.setAttribute("abc",request.getParameter("f1"))
20 | P a g e
WC invokes --- session.setAttribute("abc",request.getparameter("f1"));
WC
pageContext.setAttribute("details",session.getAttribute("abc"));
${cat}<br/>
</c:forEach>
WC invokes ---
out.print(cat);
eg :
</c:forEach>
http://localhost:8080/day6_web/close_acct.jsp?acId=101
formaction="transactions.jsp" /></td>
formaction="transactions.jsp" /></td>
<%
request.getPrameter("btn").equals("Deposit") ---
%>
....
</c:if>
in deposit
21 | P a g e
</c:if>
in withdraw
</c:if>
http://localhost:8080/day6_web/transactions.jsp?acId=102&amount=500&btn=Deposit
<c:redirect url="${sessionScope.my_bank.closeAccount()}"/>
WC --- response.sendRedirect(session.getAttribute("my_bank").closeAccount());
----------------
logout.jsp
clean up dao
invalidate sess.
auto redirect
<a href="${abc}">Next</a>
items -- any JB 's prop --- array based,coll based (List or set) map based.
Java syntax
for(Category c : categories)
out.write(c.getName()
2. declarativally -- either using Java annotations OR using XML config files (web.xml)
===============================================================================================
3. requestScope - a Map that contains request-scoped attribute names and their values.
4. sessionScope - a Map that contains session-scoped attribute names and their values.
5. applicationScope - a Map that contains application-scoped attribute names and their values.
6. param - a Map that contains rq. parameter names to a single String paramete value (obtained by calling
ServletRequest.getParameter(String name)).
7. paramValues - a Map that contains rq. param name to a String[] of all values
8. initParam - a Map that contains context initialization parameter names and their
eg : ${initParam.db_drvr}
eg : ${cookie.cookiename.value}
value ---javax.servlet.http.Cookie
${cookie.JSESSIONID.value}
---cookie.get("JSESSIOIND").getValue()
Throwable : ${pageContext.errorData.throwable}
eg :
${sessionScope.abc}
===============================================================================================
Why ????
For tracking the clnt (clnt's session) : the only information, WC needs from the clnt browser is JSessionID value. If
clnt browser is not sending it using cookie : Servlet/JSP prog can embed the JSessionID info in each outgoing URL .
What is URL Rewriting : Encoding the URL to contain the JSEssionID info.
23 | P a g e
W.C always 1st chks if JsessionID is coming from cookie, if not ---> then it will chk in URL : if it finds JseesionID from
the encoded URL : extracts its value & proceeds in the same manner as earlier.
How to ?
API :
HttpServletResponse method
Rets : origURL;JSESSIONID=12345
HttpServletResponse method
Rets : redirectURL;JSESSIONID=12345
===============================================================================================
What is Hibernate ?
0. Complete solution to the problem of managing persistence in Java.
1. ORM tool.(Object Relational Mapping) used mainly in data access layer or DAO layer.
JPA vs Hibernate
Provides automatic & transparent persistence framework to store & retrieve data from database.
Open Source Java based framework founded by Gavin King in 2001, hosted on hibernate.org
EclipseLink,iBATIS,Kodo etc.
WHY Hibernate?
It mediates the applications interaction with a relational database, leaving the developer free to concentrate on the
business problem at hand.
J2EE developer does not have to use JDBC API & manage data persistence at RDBMS level.
One has to bootstrap Hibernate framework , create transient(=not yet persistent) POJOs & then rely entirely on
Hibernate frmwork to manage persistence
24 | P a g e
ref : why hibernate readme
--------------------
Details
Formally referred as -- Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch)
1. Granularity
3. Identity
4. Associations
5. Data Navigation
Cost of Mismatch
4. Transaction management
5. Caching
6. Connection pooling
Hibernate Frmwork --- popular ORM Tool ---JPA (Java perssitence API) provider
Hibernate 4.x --- JPA compliant --- Java persistence API --- Its part of J2EE specifications. ---Is fully JPA compliant
Dev MUST add hibernate JARs ---while deploying appln on web server. Need not add JPA provider JARs , while
working on appln server.
Transparent persistence provider.(As POJOs or Entities are not bound to any Persistence API --- its written
completely independent of Persistence Provider.)
--caches data which is fetched repeatedly (via L1 & L2 cache) -- thus reduces DB traffic(L1 cache - at session level --
built in. L2 cache - pluggable) (More on caching at end of document)
(Meaning --- Lazy fetchingThe associated object or collection is fetched lazily, when its first accessed. This results in a
new request to the database (unless the associated object is cached). Eager fetchingThe associated object or
collection is fetched together with the owning object, using an SQL outer join, and no further database request is
required.
25 | P a g e
--Hibernate usually obtains exactly the right lock level automatically . so developer need not worry about applying
Read/Write lock.
Some basics
2.The objects to be persisted(called as POJO or Entity) are defined in a mapping document or marked with
annotations.
Either these HBM XML docs or annotations serves to describe the persistent fields and associations, as well as any
subclasses or proxies of the persistent object.
3.The mapping documents or annotations are compiled at application startup time and provide the framework with
necessary information for a persistent class.
An instance of Hib Configuration allows the application to specify properties and mapping documents to be used at
the frmwork start-up.
The SessionFactory provides the mechanism for managing persistent classes, the Session interface.
6.A web application or Java SE apllication will create a single Configuration, build a single instance of SessionFactory
and then instantiate multiple Sessions in threads servicing client requests.
SessionFactory : immutable and does not reflect any changes done later to the Configuration.
7. The Session class provides the interface between the persistent data store and the application.
The Session interface wraps a JDBC connection, which can be user-managed or controlled by Hibernate.
Hibernate Session
A Hibernate Session is a set of managed entity instances that exist in a particular data store.
You manage entity instances(or POJOs) by invoking operations on the entity/POJO using EntityManager/Session
instance.
Entity instances are in one of four states (2 imp aspects of it : its asso. with the hibernate session & sync of its state
with the underlying DB)
New entity instances have no persistent identity and are not yet associated with a hib. session (transient)
Managed entity instances have a persistent identity and are associated with a hib. session.(persistent : via save() or
saveOrUpdate()) Changes to DB will be done when tx is commited.
Detached entity instances have a persistent identity and are not currently associated with a persistence context/Hib
session.
Removed entity instances have a persistent identity, are associated with a persistent context and are scheduled for
removal from the data store.(removed via session.delete(obj))
26 | P a g e
Introduction to Hibernate Caching
While working with Hibernate web applications we will face so many problems in its performance due to database
traffic. That too when the database traffic is very heavy . Actually hibernate is well used just because of its high
performance only. So some techniques are necessary to maintain its performance.
The performance of Hibernate web applications is improved using caching by optimizing the database applications.
The cache actually stores the data already loaded from the database, so that the traffic between our application and
the database will be reduced when the application want to access that data again.
At maximum the application will work with the data in the cache only. Whenever some another data is needed, the
database will be accessed. Because the time needed to access the database is more when compared with the time
needed to access the cache. So obviously the access time and traffic will be reduced between the application and the
database.
Here the cache stores only the data related to current running application. In order to do that, the cache must be
cleared time to time whenever the applications are changing.
Ret type = T
In load --- if id doesn't exist & u are accessing it from within hib session --- throws ObjectNotFoundExc
2. In get --- Hibernate uses eager fetching policy ---- meaning will generate select query always & load the state from
DB in persistent POJO ref. --- so even if u access the same from within the session(persistent pojo) or outside
(detached) the hib session --- NO EXCEPTION(proxy + state)
3. In load --- Hib uses lazy fetching policy ---- meaning it will , by default NOT generate any select query --- so what u
have is ONLY PROXY(wrapper ---with no state loaded from DB) --- on such a proxy --- if u access anything outside the
hib session(detached) ----
Fix --- 1. Change fetch type --- to eager (NOT AT ALL reco.=> no caching , disabling L1 cache)
2. If u want to access any POJO in detached manner(i.e outside hib session scope) -
fire non-id get method from within session & then hib has to load entire state from DB ---NO LazyInitializationExc
Update():- if you are sure that the session does not contain an already persistent instance with the same identifier
then use update to save the data in hibernate. If session has such object with same id , then it throws ---
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated
with the session:
27 | P a g e
Merge():-if you want to save your modificatiions at any time with out knowing about the state of an session then use
merge() in hibernate.
When a client requests an entity(eg - Course POJO) and its associated graph of objects(eg -Student POJO) from the
database, it isnt usually necessary to retrieve the whole graph of every (indirectly) associated
object. You wouldnt want to load the whole database into memory at once;
eg: loading a single Category shouldnt trigger the loading of all Items in that category(one-->many)
----------------------------------------------------------
What is Session?
---------------------
hibernate application
CRUD operations
Example
What is SessionFactory?
-------------------------------
object
be created only once for an application(typically @ appln start up time) -- typically one per DB per web application.
Its immutable --- Once SF is created , changes made to hibernate.cfg.xml will not be auto reflected in SF.
28 | P a g e
What is Configuration Object ?
------------------------------------------
SessionFactory object.
object ,hibernate configuration file(hibernate.cfg.xml from run time classpath) and mapping
---------------------
Hibernate provides basic or primitive connection pool -- useful only for classroom testing.
Replace it by 3rd party vendor supplied connection pools(eg Apache or C3P0 or hikari in spring boot) for production
grade applications.
-----------------------
If u have User reg system -- then u have a business rule that --- user email must be distinct. So if u want to make this
as a prim key --then user will have to supply this during regsitration.
This is called as natural key. Since its value will be user supplied , u cant tell hibernate to generate it for u---i.e cant
use @GeneratedValue at all.
Where as -- if u say I will reserve user id only for mapping purposes(similar to serial no ), it need not come from user
at all & can definitely use hib. to auto generate it for u---this is ur surrogate key & can then use @GeneratedValue.
==============================================================================================\
WHY Hibernate?
There are many advantages of Hibernate Framework over JDBC
2) Fast performance: The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second level cache. First level
cache is enabled bydefault.
29 | P a g e
3) Database Independent query: HQL (Hibernate Query Language) / JPQL (Java persistence query language) is the
object-oriented version of SQL. It generates the database independent queries. So you don't need to write database
specific queries. Before Hibernate, If database is changed for the project, we need to change the SQL query as well
that leads to the maintenance problem.
4) Automatic table creation: Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.
5) Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework.
c_id inner join dac_students s on cs.s_id = s.stud_id group by c.id order by count(*) desc;
JPQL -- select c from Course c join fetch c.students group by c.id order by count(*) desc
6) Provides query statistics and database status: Hibernate supports Query cache and provide statistics about query
and database status.
----------------------
Advantages of hibernates:
2. In hibernate if we save the derived class object, then its base class object will also be stored into the database, it
means hibernate supporting inheritance
4. This will also supports collections like List,Set,Map (Only new collections)
5. In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we
only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate
we have the translator which converts checked to Un-checked ;)
6. Hibernate has capability to generate primary keys automatically while we are storing the records into database
7. Hibernate has its own query language, i.e hibernate query language which is database independent
So if we change the database, then also our application will works as HQL is database independent
8. While we are inserting any record, if we dont have any particular table in the database, JDBC will rises an error like
View not exist, and throws exception, but in case of hibernate, if it not found any table in the database this will
create the table for us ;)
9. Hibernate supports caching mechanism by this, the number of round trips between an application and the
database will be reduced, by using this caching technique an application performance will be increased
automatically.
30 | P a g e
10. Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods
provided by that API.
Hibernate API
0. SessionFactory API
getCurrentSession vs openSession
Opens new session , if one doesn't exist , otherwise continues with the exisitng one.
Gets automatically closed upon Tx boundary or thread over(since current session is bound to current thread --
mentioned in hibernate.cfg.xml property ---current_session_context_class ---thread)
save() method auto persists transient POJO on the DB(upon committing tx) & returns unique serializable ID
generated by (currently) hib frmwork.
T -- type of POJO
int id=101;
BookPOJO b1=hibSession.get(BookPOJO.class,id);
BookPOJO b1=(BookPOJO)hibSession.get(Class.forName("pojos.BookPOJO"),id);
using HQL -- Hibernate Query Language/JPQL --- Objectified version of SQL --- where table names will be replaced by
POJO class names & table col names will replaced by POJO property names.
31 | P a g e
2.1 Create Query Object --- from Session i/f
eg : Query<Book> q=hs.createQuery(hql/jpql,Book.class);
List<T> getResultList()
Execute a SELECT query and return the query results as a generic List<T>.
eg : hs,tx
try {
List<Book> l1=hs.createQuery(jpql,Book.class).getResultList();
Usage ---
List<BookPOJO> l1=hibSession.createQuery(hql).getResultList();
Objective : Display all books from specified author , with price < specified price.
String hql="select b from BookPOJO b where b.price < :sp_price and b.author = :sp_auth";
org.hibernate.query.Query<T> API
List<Book> l1 =
hibSession.createQuery(hql,Book.class).setParameter("sp_price",user_price).setParameter("sp_auth",user_auth).get
ResultList();
32 | P a g e
4.Updating POJOs --- Can be done either with select followed by update or ONLY with update queries(following is eg
of 2nd option--Bulk update scenario)
String jpql = "update BookPOJO b set b.price = b.price - :disc where b.author = :au and b.publishDate < :dt ";
---This approach is typically NOT recommended often, since it bypasses L1 cache . Cascading is not supported.
Doesn't support optismistic locking directly.
5. Delete operations.
API of org.hibernate.Session
---POJO is marked for removal , corresponding row from DB will be deleted after comitting tx & closing of session.
OR
5.5
One can use directly "delete HQL" & perform deletions.(Bulk delete)
eg
API of org.hibernate.query.Query<T>
Return the query results as an Iterator. If the query contains multiple results per row, the results are returned
Object[].
Pagination
Set the maximum number of rows to retrieve. If not set, there is no limit to the number of rows retrieved.
Set the first row to retrieve. If not set, rows will be retrieved beginnning from row 0. (NOTE row num starts from 0)
33 | P a g e
4.How to count rows & use it in pagination techniques?
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
selectQuery.setMaxResults(pageSize);
5. org.hibernate.query.Query API
<T> T getSingleResult()
Throws:
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement
Return the query results as ScrollableResults. The scrollability of the returned results depends upon JDBC driver
support for scrollable ResultSets.
Its a technique to group the HQL statements in single location(typically in POJOS) and lately refer them by some
name whenever need to use them. It helps largely in code cleanup because these HQL statements are no longer
scattered in whole code.
34 | P a g e
Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an
error.
Reusable: They can be accessed and used from several places which increase re-usability.
@Entity
@NamedQueries
Usgae
Department d1 = (Department)
session.getNamedQuery(DepartmentEntity.GET_DEPARTMENT_BY_ID).setInteger("id", 1);
l1 = q.list();
Well adapted for dynamic search functionalities where complex Hibernate queries have to be generated 'on-the-fly'.
Typical steps are -- Create a criteria for POJO, add restrictions , projections ,add order & then fire query(via list() or
uniqueResult())
Must be Serializable.
persist ---
if u give some non-null id (existing or non-existing) while calling persist(ref) --gives exc
35 | P a g e
why its taken as detached ? ---non null id.
2.
save --- if u give some non-null id(existing or non-existing) while calling save(ref) --doesn't give any exc.
3. saveOrUpdate
non-null BUT non existing id -- throws StaleStateException --to indicate that we are trying to delete or update a row
that does not exist.
3.5
merge
non-null BUT non existing id -- no exc thrown --Ignores ur passed id & creates its own id & inserts a
row.(select,insert)
4. get vs load
& LazyInitilalizationException
5. update
Session API
Update the persistent instance with the identifier of the given detached instance.
Exception associated :
i.e while calling update if u give null id. (transient ----X ---persistent via update)
2. org.hibernate.StaleStateException --to indicate that we are trying to delete or update a row that does not exist.
3.
36 | P a g e
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated
with the session
1. The state of a transient or detached instance may also be made persistent as a new persistent instance by calling
merge().
2. API of Session
3.
Copies the state of the given object(can be passed as transient or detached) onto the persistent object with the
same identifier.
3.If there is no persistent instance currently associated with the session, it will be loaded.
4.Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent
instance. The given instance does not become associated with the session.
5. will not throw NonUniqueObjectException --Even If there is already persistence instance with same id in session.
(Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. )
8.
void clear()
When clear() is called on session object all the objects associated with the session object(L1 cache) become
detached.
(Completely clears the session. Evicts all loaded instances and cancel all pending saves, updates and deletions)
9. void close()
the persistent objects associated with the session object become detached(l1 cache is cleared) and also closes the
Database Connection.
When the object is in persistent state , whatever changes we made to the object
37 | P a g e
call the flush method.
(Flushing is the process of synchronizing the underlying DB state with persistable state of session cache )
12.
This method is used to get the latest data from database and make
(Re-reads the state of the given instance from the underlying database
=========================================================================
Hibernate Association
The two rules, for bidirectional one-to-one associations
1 The @JoinColumn annotation goes on the mapping of the entity that is mapped to
the table containing the join column, or the owner of the relationship. This might
entity that does not define a join column, or the inverse side of the relationship.
Hibernate will assume each side was the owner and each will have a join column.
----------------
When an entity is associated with a Collection of other entities, it is in form of a one-to-many mapping.
When a relationship is bidirectional, there are actually two mappings, one for each direction.
A bidirectional one-to-many relationship always implies a many-to-one mapping back to the source.
When a Course entity has an number of Student entities stored in its collection, there is no definite way to store
those references in the database table.
Instead Student table MUST have foreign keys back to the Course
So the one-to-many association is almost always bidirectional and never the owning side.
38 | P a g e
In Course entity u need to map the Students with @OneToMany annotation.
Since this is the inverse side of the relationship, MUST include the mappedBy attribute.
eg : In Course Entity
mappedBy -- must refer to the prop name in the associated table --to specify ownership of the asso.
---mappedBy tells hibernate that instead of having a separate join table --map students by course i.e course = name
of the property appearing in Student class , anno by @ManyToOne
In Student Entity
@ManyToOne
@JoinColumn(name = "course_id")
Rules
1. The many-to-one side is the owning side, so the join column is defined on that
side.
2. The one-to-many mapping is the inverse side, so the mappedBy element must be
used.
---------------------------------
BUT collections of embeddable and basic types are not relationships; they are simply collections of elements .
collections contain objects that are dependent upon the referencing entity, and can be retrieved only through the
entity that contains them.
BUT then hibernate creates its own table to store these embeddables
@ElementCollection
39 | P a g e
=============================================================================
1. If an object has its own database identity (primary key value) then it’s type is Entity Type.
2. An entity has its own lifecycle. It may exist independently of any other entity.
3. An object reference to an entity instance is persisted as a reference in the database (a foreign key value).
eg : College is an Entity Type. It has it’s own database identity (It has primary key).
Value Types :
1. If an object don’t have its own database identity (no primary key value) then it’s type is Value Type.
3. It’s embedded in the owning entity and it represents the table column in the database.
4. The lifespan of a value type instance is bounded by the lifespan of the owning entity instance.
Basic value types are : they map a single database value (column) to a single, non-aggregated Java type.
In JPA composite types also called Embedded Types. Hibernate traditionally called them Components.
2.1 Composite Value type looks like exactly an Entity, but does not own lifecycle and identifier.
Annotations Used
1. @Embeddable :
Defines a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the
entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the
entity. It doesn't have own identifier.
eg : Address is eg of Embeddable
Student HAS-A Address(eg of Composition --i.e Address can't exist w/o its owning Entity i.e Student)
College HAS-A Address (eg of Composition --i.e Address can't exist w/o its owning Entity i.e College)
BUT Student will have its own copy of Address & so will College(i.e Value Types don't support shared reference)
2. @Embedded :
Specifies a persistent field or property of an entity whose value is an instance of an embeddable class. The
embeddable class must be annotated as Embeddable.
3. @AttributesOverride :
40 | P a g e
Used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.
In Database tables observe the column names. Student table having STREET_ADDRESS column and College table
having STREET column. These two columns should map with same Address field streetAddress. @AttributeOverride
gives solution for this.
To override multiple column names for the same field use @AtributeOverrides annotation.
eg : In Student class :
@Embedded
@AttributeOverride(name="streetAddress", column=@Column(name="STREET_ADDRESS"))
But Collection value Types can be either collection of Basic value types, Composite types and custom types.
eg :
Collection mapping means mapping group of values to the single field or property. But we can’t store list of values in
single table column in database. It has to be done in a separate table.
eg : Collection of embeddables
@ElementCollection
@CollectionTable(name="CONTACT_ADDRESS", joinColumns=@JoinColumn(name="USER_ID"))
@AttributeOverride(name="streetAddress", column=@Column(name="STREET_ADDRESS"))
@ElementCollection
@CollectionTable(name="Contacts", joinColumns=@JoinColumn(name="ID"))
@Column(name="CONTACT_NO")
================================================================================
Hibernate API
0. SessionFactory API
getCurrentSession vs openSession
Opens new session , if one doesn't exist , otherwise continues with the exisitng one.
41 | P a g e
Gets automatically closed upon Tx boundary or thread over(since current session is bound to current thread --
mentioned in hibernate.cfg.xml property ---current_session_context_class ---thread)
save() method auto persists transient POJO on the DB(upon committing tx) & returns unique serializable ID
generated by (currently) hib frmwork.
T -- type of POJO
int id=101;
BookPOJO b1=hibSession.get(BookPOJO.class,id);
BookPOJO b1=(BookPOJO)hibSession.get(Class.forName("pojos.BookPOJO"),id);
using HQL -- Hibernate Query Language/JPQL --- Objectified version of SQL --- where table names will be replaced by
POJO class names & table col names will replaced by POJO property names.
eg : Query<Book> q=hs.createQuery(hql/jpql,Book.class);
List<T> getResultList()
Execute a SELECT query and return the query results as a generic List<T>.
eg : hs,tx
42 | P a g e
String jpql="select b from Book b";
try {
List<Book> l1=hs.createQuery(jpql,Book.class).getResultList();
Usage ---
List<BookPOJO> l1=hibSession.createQuery(hql).getResultList();
Objective : Display all books from specified author , with price < specified price.
String hql="select b from BookPOJO b where b.price < :sp_price and b.author = :sp_auth";
org.hibernate.query.Query<T> API
List<Book> l1 =
hibSession.createQuery(hql,Book.class).setParameter("sp_price",user_price).setParameter("sp_auth",user_auth).get
ResultList();
4.Updating POJOs --- Can be done either with select followed by update or ONLY with update queries(following is eg
of 2nd option--Bulk update scenario)
String jpql = "update BookPOJO b set b.price = b.price - :disc where b.author = :au and b.publishDate < :dt ";
---This approach is typically NOT recommended often, since it bypasses L1 cache . Cascading is not supported.
Doesn't support optismistic locking directly.
5. Delete operations.
API of org.hibernate.Session
43 | P a g e
---POJO is marked for removal , corresponding row from DB will be deleted after comitting tx & closing of session.
OR
5.5
One can use directly "delete HQL" & perform deletions.(Bulk delete)
eg
API of org.hibernate.query.Query<T>
Return the query results as an Iterator. If the query contains multiple results per row, the results are returned
Object[].
Pagination
Set the maximum number of rows to retrieve. If not set, there is no limit to the number of rows retrieved.
Set the first row to retrieve. If not set, rows will be retrieved beginnning from row 0. (NOTE row num starts from 0)
selectQuery.setFirstResult((lastPageNumber - 1) * pageSize);
selectQuery.setMaxResults(pageSize);
5. org.hibernate.query.Query API
<T> T getSingleResult()
44 | P a g e
Returns: Returns a single instance(persistent) that matches the query.
Throws:
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement
Return the query results as ScrollableResults. The scrollability of the returned results depends upon JDBC driver
support for scrollable ResultSets.
Its a technique to group the HQL statements in single location(typically in POJOS) and lately refer them by some
name whenever need to use them. It helps largely in code cleanup because these HQL statements are no longer
scattered in whole code.
Fail fast: Their syntax is checked when the session factory is created, making the application fail fast in case of an
error.
Reusable: They can be accessed and used from several places which increase re-usability.
@Entity
@NamedQueries
Usgae
Department d1 = (Department)
session.getNamedQuery(DepartmentEntity.GET_DEPARTMENT_BY_ID).setInteger("id", 1);
l1 = q.list();
Well adapted for dynamic search functionalities where complex Hibernate queries have to be generated 'on-the-fly'.
Typical steps are -- Create a criteria for POJO, add restrictions , projections ,add order & then fire query(via list() or
uniqueResult())
45 | P a g e
Rules on prim key class
Must be Serializable.
persist ---
if u give some non-null id (existing or non-existing) while calling persist(ref) --gives exc
save --- if u give some non-null id(existing or non-existing) while calling save(ref) --doesn't give any exc.
3. saveOrUpdate
non-null BUT non existing id -- throws StaleStateException --to indicate that we are trying to delete or update a row
that does not exist.
3.5 merge
non-null BUT non existing id -- no exc thrown --Ignores ur passed id & creates its own id & inserts a
row.(select,insert)
4. get vs load
& LazyInitilalizationException.
5. update
Session API
46 | P a g e
public void update(Object object)
Update the persistent instance with the identifier of the given detached instance.
Exception associated :
i.e while calling update if u give null id. (transient ----X ---persistent via update)
2. org.hibernate.StaleStateException --to indicate that we are trying to delete or update a row that does not exist.
3.
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated
with the session
1. The state of a transient or detached instance may also be made persistent as a new persistent instance by calling
merge().
2. API of Session
3.
Copies the state of the given object(can be passed as transient or detached) onto the persistent object with the
same identifier.
3.If there is no persistent instance currently associated with the session, it will be loaded.
4.Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent
instance. The given instance does not become associated with the session.
5. will not throw NonUniqueObjectException --Even If there is already persistence instance with same id in session.
(Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. )
8. void clear()
When clear() is called on session object all the objects associated with the session object(L1 cache) become
detached.
(Completely clears the session. Evicts all loaded instances and cancel all pending saves, updates and deletions)
9. void close()
47 | P a g e
When close() is called on session object all
the persistent objects associated with the session object become detached(l1 cache is cleared) and also closes the
Database Connection.
When the object is in persistent state , whatever changes we made to the object
(Flushing is the process of synchronizing the underlying DB state with persistable state of session cache )
This method is used to get the latest data from database and make
(Re-reads the state of the given instance from the underlying database
===============================================================================================
Spring
Why Spring
Allows to build applications using loose coupling achieved via IoC(Inversion of control) & AOP(aspect oriented
programming)
What is it ?
It is a container + framework.
Why Container
It manages the life cycle of spring beans (eg : controller,rest controller , dao,service)
Why Framework ?
It is the most popular application development framework for enterprise Java. It is used to create high performant,
easily testable, and reusable code.
Founder is Rod Johnson and was first released under the Apache license in June 2003.
48 | P a g e
Currently hosted on Pivotal/VMware
Why Spring
2. It supports in developing any Java application, but there are extensions(web MVC) for building web applications
on top of the Java EE platform.
3. It helps programmers to make J2EE development easier to use and promotes good programming practices by
enabling a POJO-based programming model.
Spring's web framework is a web MVC framework, which is a great alternative to web frameworks such as Struts
7. It is organized in a modular fashion. Even though it's extensive , you have to worry only about the those modules
that you need and ignore the rest.
8. Spring does not re-invent the wheel, instead it makes use of already existing frameworks like Hibernate , making
its integration easier.
9. It translates technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent,
unchecked exceptions.
10. It provides a consistent transaction management interface that can support a local transaction (using a single
database) as well as global transactions (using JTA over multiple databases).
===============================================================================================
1.1 The Core module provides the fundamental parts of the framework, including the IoC based upon Dependency
Injection
1.2 The Bean module provides BeanFactory , which is a readymade implementation of the factory pattern.
1.3 The Context module is based upon the Core and Beans modules .It provides a way to access any spring
beans(objects managed by Spring container) which are defined and configured. The ApplicationContext interface is
the heart of Context module.
1.4 The SpEL module provides a powerful expression language for querying and manipulating an object graph at
runtime.
49 | P a g e
2. Data Access/Integration module
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules
2.1 The JDBC module provides a JDBC-abstraction layer that removes the need for boilerplat JDBC related coding.
2.2 The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO,
Hibernate, and iBatis.
2.3 The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB,
XMLBeans, , XStream etc
2.4 JMS module contains features for producing and consuming messages sent across application components
2.5 The Transaction module supports programmatic and declarative transaction management for typically service
layer or DAO layer spring beans.
3. Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules .
The Web module provides basic web integration features such as MVC support,multipart file-upload functionality
,init of IoC container using servlet listeners , web application context , I18N etc.
3.1 The Web-MVC module contains Spring's Model-View-Controller (MVC) implementation for web applications.
3.2 The Web-Socket module provides support for WebSocket-based, two-way communication between the client
and the server in web applications.
3.3 The Web-Portlet module provides the MVC implementation to be used in a portlet environment
1. The AOP module provides an aspect-oriented programming implementation allowing you to define method-
interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.
3. The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in web socket
applications.
4. The Test module supports the testing of Spring components with JUnit or TestNG frameworks.
======================================================================================
Spring 4 DB Transactions
Required JARS ---org.springframework.transaction & aop jars
Basics
* Very easy to use, does not require any underlying transaction API knowledge
What is a Transaction?
50 | P a g e
A Transaction is a unit of work performed on the database and treated in a reliable way independent of other
transaction. In database transaction processing ACID property refers to the Atomicity, Consistency, Isolation,
Durability respectively.
Atomicity- This property says that all the changes to the data is performed as if they form single operation. For
example suppose in a bank application if a fund transfer from one account to another account the atomicity
property ensures that is a debit is made successfully in one account the corresponding credit would be made in
other account.
Consistency- The consistency property of transaction says that the data remains in the consistence state when the
transaction starts and ends. for example suppose in the same bank account, the fund transfer from one account to
another account, the consistency property ensures that the total value(sum of both account ) value remains the
same after the transaction ends.
Isolation- This property says that, the intermediate state of transaction are hidden/ invisible to another transaction
process.
Durability- The Durability says that when the transaction is completed successfully, the changes to the data persist
and are not un-done, even in the event of system failure.A transaction is not considered durable until it commits. A
system failure entails a database recovery, which includes a rollback procedure for all uncommitted transactions,
ultimately leaving the database in a consistent state.
Transaction Handling
Now, in Java you can handle transactions with plain SQL, with plain JDBC (a bit higher level), using Hibernate (or any
other ORM library), or on an even higher level - with EJB or, finally, Spring!
EJBs require an application server, but spring based jdbc application doesn't.
Spring offers two ways of handling transactions: programmatic and declarative. If you are familiar with EJB
transaction handling, this corresponds to bean-managed and container-managed transaction management.
Programmatic means you have transaction management code surrounding your business code. That gives you
extreme flexibility, but is difficult to maintain and too much of boilerplate code.
Declarative means you separate transaction management from the business code. You only use annotations or XML
based configuration.
As a summary
* programmatic management is more flexible during development time but less flexible during application life
* declarative management is less flexible during development time but more flexible during application life
Global transactions enable you to work with multiple transactional resources, typically multiple relational databases
. The application server manages global transactions through the JTA. (complex to use through UserTransaction
object)
Local Transactions
Local transactions are resource-specific, such as a transaction associated with a JDBC connection. Local transactions
may be easier to use, but have significant disadvantages as they cannot work across multiple transactional
resources.
Spring's solution
51 | P a g e
Spring resolves the disadvantages of global and local transactions. It enables application developers to use a
consistent programming model in any environment. You write your code once, and it can benefit from different
transaction management strategies in different environments. It supports both declarative and programmatic
transaction management. Most users prefer declarative transaction management.
API details
1. The key to the Spring transaction abstraction is the notion of a transaction strategy. Its the central interface in
Spring's transaction infrastructure. A transaction strategy is defined by the
org.springframework.transaction.PlatformTransactionManager
TransactionException --- As in Spring's philosophy, the TransactionException that is thrown by any of the
PlatformTransactionManager interface's methods , is unchecked Transaction infrastructure failures are generally
fatal , managed by spring Tx frmwork & developer is NOT forced to handle this.
Isolation: The degree to which this transaction is isolated from the work of other transactions.
* Lost update - two transactions both update a row, the second transaction aborts, both changes are lost
* Unrepeatable read - a transactions reads twice the same row, getting different data each time
* Phantom read - similar to the previous one, except that the number of rows changed
Now, the perfect solution to these problems is maximum isolation, but in reality this would cost too much resources
and could lead to deadlocks. So, instead, you will set one of five isolation levels (where the fifth one is actually the
maximum isolation level):
Supported levels
ISOLATION_READ_UNCOMMITTED --- Indicates that dirty reads, non-repeatable reads and phantom reads can
occur.
ISOLATION_READ_COMMITTED --- Indicates that dirty reads are prevented; non-repeatable reads and phantom
reads can occur.
ISOLATION_REPEATABLE_READ -- Indicates that dirty reads and non-repeatable reads are prevented; phantom
reads can occur.
ISOLATION_SERIALIZABLE -- Indicates that dirty reads, non-repeatable reads and phantom reads are prevented.
Transaction Propagation
Whenever a one transactional method calls other transactional mehod , a decision is made - what to do with the
transaction. Create a new one? Use an existing one if it exists, otherwise create a new one? Use an existing one only
if it exists, otherwise fail?
52 | P a g e
Supports a current transaction; creates a new one if none exists.
NESTED ---Executes within a nested transaction if a current transaction exists, otherwise same as REQUIRED
SUPPORTS
REQUIRES_NEW
NEVER
Does not support a current transaction; throws an exception if a current transaction exists.
NOT_SUPPORTED
Timeout: in seconds .How long this transaction runs before timing out and being rolled back automatically by the
underlying transaction infrastructure.
eg
@Transactional(timeout=100)
Read-only status: A read-only transaction can be used when your code reads but does not modify data.
Read-only transactions can be a useful optimization in some cases, such as when you are using Hibernate.
eg -- @Transactional(readOnly = true)
default is false.
Rollback behavior
With Spring transaction management the default behavior for automatic rollback is this: Only unchecked exceptions
cause a rollback. Unchecked exceptions are RuntimeExceptions and Errors.But can be changed.
eg --
Implementation steps & concept for annotation based declarative transaction management.
p:dataSource-ref="dataSource">
</bean>
53 | P a g e
3. To enable annotated transaction support , add transaction namespace(tx) & add following
4. In service layer beans (typically annotated with @Service) , add method level annotation @Transactional along
with suitable properties.
===============================================================================================
Hibernate Caching
Caching is a facility provided by ORM frameworks which help users to get fast running web application, while help
framework itself to reduce number of queries made to database in a single transaction.
First level cache in hibernate is enabled by default and you do not need to do anything to get this functionality
working. In fact, you can not disable it even forcefully.(typically)
Session object is created on demand from session factory and it is lost, once the session is closed.
Similarly, first level cache associated with session object is available only till session object is live. It is available to
session object only and is not accessible to any other session object in any other part of application.
NOTE
1. First level cache is associated with session object and other session objects in application can not see it.
2. The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
3. First level cache is enabled by default and you can not disable it.
4. When we query an entity first time, it is retrieved from database and stored in first level cache associated with
hibernate session.
5. If we query same object again with same session object, it will be loaded from cache and no sql query will be
executed.(completely true only for get or load)
6. The loaded entity can be removed from session using evict(Object ref) method. The next loading of this entity
will again make a database call if it has been removed using evict() method.
7. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.
#####################
Caching is facility provided by ORM frameworks which help users to get fast running web application, while help
framework itself to reduce number of queries made to database in a single transaction. Hibernate also provide this
caching functionality, in two layers.
Fist level cache: This is enabled by default and works in session scope. Read more about hibernate first level cache.
Second level cache: This is apart from first level cache which is available to be used globally in session factory scope.
Above statement means, second level cache is created in session factory scope and is available to be used in all
sessions which are created using that particular session factory.
It also means that once session factory is closed, all cache associated with it die and cache manager also closed
down.
54 | P a g e
How second level cache works?
1. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level
cache (associated with particular hibernate session).
2. If cached copy of entity is present in first level cache, it is returned as result of load/get method.
3.If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
4.If second level cache has cached entity, it is returned as result of load/get method. But, before returning the entity,
it is stored in first level cache also so that next invocation to load method for entity will return the entity from first
level cache itself, and there will not be need to go to second level cache again.
If entity is not found in first level cache and second level cache also, then database query is executed and entity is
stored in both cache levels, before returning as response of load() method.
============================================================================================
3. Add DispatcherServlet entry in web.xml -- to ensure all request pass through central dispatcher servlet.
4. Create spring-servlet.xml under <WEB-INF> -- To allow D.S to create Web application context using master config
xml file.
POJO properites --- represent 1. DB cols 2.Request params --i.e clnt's conversational state.
No need to manage Txs --directly get session from SF & perform CRUD operation.
=========================================================================================
Hibernate Inheritance
Inheritance is one of the fundamental design principles in OOP. BUT relational databases don’t support
inheritance
In this inheritance, a single table is used to store all the instances of the entire inheritance hierarchy. The Table will
have a column for every attribute of every class in the hierarchy. Discriminator columns identifies which class a
particular row belongs.
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "emp_type")
@Table(name = "employees")
In sub class :
@Entity
@DiscriminatorValue("worker")
@Entity
@DiscriminatorValue("mgr")
With this mapping strategy, only a single table will be created for both concrete classes (Manager and Worker).
Hibernate will create a discriminator column named emp_type to differentiate each concrete type. The value of this
column will be either worker or mgr
This is the most logical solution, as it mirrors the object structure in the database. In this approach, a separate
database table is defined for each of the class in the hierarchy and each table stores only its local attributes.
56 | P a g e
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Id @GeneratedValue
@Entity
The above mapping will create two tables, one for super class Product and another for entity Book. Both the tables
will have Product id column. The primary key of table Book will have foreign key relationship with primary key of
Product table.
A separate table is defined for each concrete class in the inheritance hierarchy to store all the attribute of that class
and all its super classes.
4. @MappedSuperClass
We want to extract common behavior in a super class in JPA entities but without having a table for that super class.
How would you achieve that?
If we create a normal class as the super class, then as per JPA specifications, the fields for that class are not persisted
in the database tables. We need to create a super class extracting the common fields and then annotate that class
with @MappedSuperClass in order to persist the fields of that super class in subclass tables. A mapped super class
has no separate table defined for it.
MappedSuperClass example
@MappedSuperclass
@Id
@Entity
57 | P a g e
The above configuration will result in a single table for employee with 3 columns (id, name and company), 1 from
Employee class itself and 2 are inherited from Person class. Person class will never have its own table in this case.
============================================================================================
front controller in MVC model II . It is a common web-application pattern where a single servlet delegates
responsibility for a request to other components of an application to perform the actual processing.
3. The DispatcherServlet’s job is to send the request on to a Spring MVC controller(prog supplied)
4. As typical appln may have several controllers, DispatcherServlet consults Handler mapping to select controller.
6. Req thus reaches the controller. Controller may use one or more service layer objs for exec of B.L
The result of B.L needs to be carried back to the user and displayed in the browser. This info. is the model. It has to
be sent to JSP(or any other view template) for converting it to HTML like format.
name of a view into a ModelAndView object. It rets the request+ ModelAndView back to the DispatcherServlet.
(M&V
doesn’t carry a reference to the actual JSP but only carries a logical result name that will be used to look up the
actual view that will produce the resulting HTML.
8. DispatcherServlet now consults a view resolver to find the actual JSP. & delivers the model data to view JSP
9. The view will use the model data to render a page that will be sent as dyn resp back to the clnt browser.
object.
The ViewResolver provides a mapping between view names and actual views.
==============================================================================================
Spring Boot
Problems with traditionals/legacy spring
We use different modules from spring such as core module, to do dependency injection.The MVC module to develop
the web layer for our application or even the restful web services layer.And then the DAO layer where we use the
spring JDBC/ORM which makes our life easy to develop a data access layer for our application. When we are using
ORM tools like Hibernate, we can use spring data JPA and we use these modules and more that are valuable from
Spring.
58 | P a g e
Initially we used XML based configuration or annotations based configuration,This configuration can get difficult and
hard to maintain over time.And also we need to make sure that each of these modules is available for our
application by defining all the dependencies in the Maven pom xml.And at runtime we have to be sure that these
versions of various Modules that we use are compatible with each other.But it's our responsibility to do all that, and
once we have all that in place we will build our application and will have to deploy to an external web container to
test it .
1. The first of those super cool features is auto configuration - Spring Boot automatically configures everything that is
required for our application. We don't have to use XML or annotation based or Java configuration anymore.
For example if you are using Spring MVC or the web to develop a web application or a restful web service application
spring boot will automatically configure the dispatcher servlet and does all the request mapping for us. We don't
have to use any xml or annotation based configuration to configure this servlet.
Similarly if you are using spring data or object relational mapping while working with tools like Hibernate to perform
database crud we no longer have to configure the data source or even the transaction manager. Spring boot will
automatically configure these for our application.
2. The next super cool feature is spring boot starters .With the spring boot starters spring boot takes the problem off
module availability we need. Before Spring Boot we had to make sure that a particular library required for our
project is available and also the versions of different libraries are compatible.But we don't have to do that anymore
thanks to spring boot starters every spring boot project will have a parent project.This project has all the version
information of various libraries that we will be using in our project so we need not worry about version
compatibility. The spring developers have already done it for us and put all that information into this spring boot
starter parent .
Secondly we have starters for different types of projects if we are developing a web project then we simply need to
include the starter web . We don't have to include any other libraries or dependencies. Spring boot will automatically
pull all the other libraries that are required because this project here or this or dependency transitively depends on
other libraries that are required. Maven will automatically pull those libraries. The spring boot developers have given
us starter dependencies which when we use in our projects will not have the Modular availability problem and the
version compatibility problem.
Another example is the spring boot starter data jpa .When you want to work with Hibernate you simply include the
single dependency in your maven pom xml and all the other libraries will be pulled accordingly. And also the correct
versions of those libraries will be included because all that version information is available in this spring boot starter
parent which is a parent for every spring boot project.
3. The third super cool feature we don't have to worry about deploying our applications to external container spring
boot comes with an embedded servlet container and these containers.
By default it is Tomcat but you can also use Jetty and undertow or any other external server. So no longer external
deployment you can simply right click on your project and run it and your application will be launched on its
embedded Tomcat server by default.
4. Last and very important spring boot gives us a lot of health checks of our application for free through the spring
boot actuators.We can use different types of health checks that come for free and we can use these even on
production when our application is running. These can be activated easily and will display all the auto configuration
reports and everything that is automatically configured for our application.
@SpringBootApplication
59 | P a g e
public class HellospringbootApplication { p.s.v.m(...) {...}}
The SpringBootApplication is a key annotation which is a top level annotation which contains several other
annotations on it.
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
The first one @SpringBootConfiguration tells spring boot or the container that this class here can have several bean
definitions. We can define various spring beans here and those beans will be available at run time so you define a
method here .
The second annotation @EnableAutoConfiguration is a very important annotation at enable Auto configuration.This
annotation tells spring boot to automatically configure the spring application based on the dependencies that it sees
on the classpath.
eg:
If we have a MySql dependency in our pom.xml as automatically Spring Boot will create a data source. We will also
provide other information like username password etc. but spring boot will scan through all these dependencies and
it will automatically configure the data source required for us.
Then spring boot will automatically create the dispatcher servlet on all that configuration file you for free.
All the xml, all the java based configuration is now gone. We as developers need not do all that configuration it all
comes for free thanks to spring boots to enable auto configuration annotation.
@ComponentScan
So this tells us that spring boot or spring should scan through the classes and see which all classes are marked with
the stereotype annotations like @Component Or @Service @Repository and manage these spring beans . Default
base-pkg is the pkg in which main class is defined.
Can be overridden by
eg :
@ComponentScan(basePackages = "com")
@EntityScan(basePackages = "com.app.pojos")
===========================================================================================
Spring Boot is a Framework from "The Spring Team" to ease the bootstrapping and development of new Spring
Applications.
It provides defaults for code and annotation configuration to quick-start new Spring projects within no time.
It follows "Opinionated Defaults Configuration" an approach to avoid lot of boilerplate code and configuration to
improve Development, Unit Test and Integration Test Process.
60 | P a g e
2. What is NOT Spring Boot?
Spring Boot Framework is not implemented from the scratch by The Spring Team
It is not used for solving any new problems. It is used to solve same problems like Spring Framework.
It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring
Data, Spring Security etc.
It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy)
It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and
Gradle
It provides lots of plugins to work with embedded and in-memory Databases very easily.
In short
Spring Boot = Spring Framework + Embedded HTTP Server(eg Tomcat) - XML Based configuration - efforts in
identifying dependencies in pom.xml
When we use Hibernate/JPA, we would need to configure a datasource, a session factory, a transaction manager
among lot of other things.
Can we auto-configure a Data Source(connection pool) / session factory / Tx manager if Hibernate jar is on the
classpath?
It says :
When a spring mvc jar is added into an application, can we auto configure some beans automatically?
By the way :
Based on these, Spring Boot provides basic configuration needed to configure the application with these
frameworks. This is called Auto Configuration.
Starters are a set of convenient dependency descriptors that you can include in your application's pom.xml
W/o Spring boot , we would need to identify the frameworks we want to use, which versions of frameworks to use
and how to connect them together.
These include Spring MVC, Jackson Databind (for data binding), Hibernate-Validator (for server side validation using
Java Validation API) and Log4j (for logging). Earlier while creating any web app, we had to choose the compatible
versions of all these frameworks.
With Spring boot : You just add Spring Boot Starter Web.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Just by adding above starter , it will add lot of JARs under maven dependencies
Another eg : If you want to use Spring and JPA for database access, just include the spring-boot-starter-data-jpa
dependency in your project, and you are good to go.
7. Another cool feature of Spring boot is : we don't have to worry about deploying our applications to external
container. It comes with an embedded servlet container.
@SpringBootApplication
SpringApplication.run(HelloSpringBootApplication.class, args);
About : org.springframework.boot.SpringApplication
It's Class used to bootstrap and launch a Spring application from a Java main method.
By default class will perform the following steps to bootstrap the application
62 | P a g e
1. Create an ApplicationContext instance (representing SC)
1. @SpringBootConfiguration
It tells spring boot that this class here can have several bean definitions. We can define various spring beans here
and those beans will be available at run time .
2. @EnableAutoConfiguration
It tells spring boot to automatically configure the spring application based on the dependencies that it sees on the
classpath.
eg:
If we have a MySql dependency in our pom.xml , Spring Boot will automatically create a data source,using the
properties in application.properties file.
If we have spring web in pom.xml , then spring boot will automatically create the dispatcher servlet n other beans
(HandlerMapping , ViewResolver)
All the xml, all the java based configuration is now gone.It all comes for free thanks to spring boot to enable auto
configuration annotation.
So this tells us that spring boot to scan through the classes and see which all classes are marked with the stereotype
annotations like @Component Or @Service @Repository and manage these spring beans . Default base-pkg is the
pkg in which main class is defined.
Can be overridden by
eg :
@ComponentScan(basePackages = "com")
@EntityScan(basePackages = "com.app.pojos")
Steps
1. File --New --Spring starter project -- add project name , group id ,artifact id ,pkg names , keep packaging as JAR for
Spring MVC web application.
2. Add dependencies
web -- web
Core -- DevTools
Lombok
validation
Add following dependencies ONLY for Spring MVC with JSP as View Layer in pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Reason : Could not find org.hibernate.SessionFactory (since Spring boot DOES NOT support any native hibenrate
implementationj directly)
(refer : day17-data\day17_help\diagrams\jpa-entitymgr-session-layers.png)
i.e instead of auto wiring SF in DAO layer : inject JPA' EntityManager directly in DAO.
How ?
@PersistenceContext
//uses def persistence unit , created auto by spring boot using db setting added //in application.properties file , 1 per
app / DB
OR
=============================================================================================
@SpringBootApplication
SpringApplication.run(HelloSpringBootApplication.class, args);
About : org.springframework.boot.SpringApplication
It's Class used to bootstrap and launch a Spring application from a Java main method.
By default class will perform the following steps to bootstrap the application
1. @SpringBootConfiguration
It tells spring boot that this class here can have several bean definitions. We can define various spring beans here
and those beans will be available at run time .
2. @EnableAutoConfiguration
It tells spring boot to automatically configure the spring application based on the dependencies that it sees on the
classpath.
eg:
If we have a MySql dependency in our pom.xml , Spring Boot will automatically create a data source(Connection
Pool) ,using the properties in application.properties file.
If we have spring web in pom.xml , then spring boot will automatically create the dispatcher servlet n other beans
(HandlerMapping , ViewResolver)
All the xml, all the java based configuration is now gone.It all comes for free thanks to spring boot to enable auto
configuration annotation.
Can be overridden by
eg :
@ComponentScan(basePackages = "com")
@EntityScan(basePackages = "com.app.pojos")
===============================================================================================
How ?
1.1 For loading the form (in showForm method of the controller) , bind empty POJO (using def constr) in model map
How ?
map.addAttribute(nm,val)
OR better way
eg : User registration
@GetMapping("/reg")
What will SC do ?
chks --- Are there any req params coming from client ? --- typically --no --- only getters will be called --
map.addAttribute("user",new User());
1.2 In form (view ---jsp) -use spring form tags along with modelAttribute
Steps
2. Specify the name of modelAttribute under which form data will be exposed.(name of model attr mentioned in the
controller)
<s:input path="email"/>.....
</s:form>
66 | P a g e
clnt sends a new req --- containing req params
@PostMapping("/reg")
//SC calls
map.addAttribute("user",u)
Thus you get a populated POJO directly in controller w/o calling <jsp:setProperty> & w/o using any java bean.
==============================================================================================
Maven
What is Maven ?
It helps in
Why Maven ?
It eases out source code compilation, distribution, documentation, collaboration with different teams .
2. The dependencies, plug-ins & profiles that the project is associated in a standalone or a distributed environment.
Vendor -- Apache
Vendor -- Apache.
Ant disadvantages
1. While using ant , project structure had to be defined in build.xml. Maven has a convention to place source code,
compiled code etc. So no need to provide information about the project structure in pom.xml file.
2. Maven is declarative, everything you define in the pom.xml file.No such support in ant.
Maven advantages
4. Managing dependencies
67 | P a g e
6. Multiple/Repeated builds can be achieved.
7. Plugin management.
Contents
Plugins used
Project version
=========================================================================================
Maven Steps
1. project It is the root element of pom.xml file.
3. groupId It is the sub element of project. It specifies the id for the project group.(typically organization name)
4. artifactId It is the sub element of project. It specifies the id for the artifact (project). An artifact is something
that is either produced or used by a project. Examples of artifacts produced by Maven for a project include: JARs,
WARs.
5. version It is the sub element of project. It specifies the version of the artifact under given group.
Within that --
9. scope -- defines scope for this maven project. It can be compile, provided, runtime, test and system.
Goals in Maven
Goal in maven is nothing but a particular task which leads to the compiling, building and managing of a project. A
goal in maven can be associated to zero or more build phases. Only thing that matters is the order of the goals
68 | P a g e
defined for a given project in pom.xml. Because, the order of execution is completely dependent on the order of the
goals defined.
A maven repository is a directory of packaged JAR file with pom.xml file. Maven searches for dependencies(JARs) in
the repositories. There are 3 types of maven repository:
Local Repository
Central Repository
Remote Repository
maven repositories
If dependency is not found in these repositories, maven stops processing and throws an error.
Maven local repository is located in the file local system. It is created by the maven when you run any maven
command.
Maven central repository is located on the web(Created by the apache maven community)
Maven remote repository is also located on the web. Some of libraries that are missing from the central repository
eg JBoss library , Oracle driver etc, can be located from remote repository.
What is it ?
The sequence of steps which is defined in order to execute the tasks and goals of any maven project is known as
build life cycle in maven.
Clean - this phase involves cleaning of the project (for a fresh build & deployment)
Site - this phase handles the generating the java documentation of the project.
It is a subset of elements which allows to customize builds for particular environment. Profiles are also portable for
different build environments.
69 | P a g e
Build environment basically means a specific environment set for production and development instances. When
developers work on development phase, they use test database from the production instance and for the
production phase, the live database will be used.
So, in order to configure these instances maven provides the feature of build profiles. Any no. of build profiles can be
configured and also can override any other settings in the pom.xml
4.Verify maven
mvn -- version
===============================================================================================
REST
Background
Web services have really come a long way since its inception. In 2002, the World Wide Web consortium(W3C) had
released the definition of WSDL(web service definition language) and SOAP web services. This formed the standard
of how web services are implemented.
In 2004, the web consortium also released the definition of an additional standard called RESTful. Over the past
couple of years, this standard has become quite popular. And is being used by many of the popular websites around
the world which include Facebook and Twitter.
REST is a way to access resources which lie in a particular environment. For example, you could have a server that
could be hosting important documents or pictures or videos. All of these are an example of resources. If a client, say
a web browser needs any of these resources, it has to send a request to the server to access these resources. Now
REST defines a way on how these resources can be accessed.
eg of a web application which has a requirement to talk to other applications such Facebook, Twitter, and Google.
Now if a client application had to work with sites such as Facebook, Twitter, etc. they would probably have to know
what is the language Facebook, Google and Twitter are built on, and also on what platform they are built on.
Based on this, we can write the interfacing code for our web application, but this could prove to be a nightmare.
So instead , Facebook, Twitter, and Google expose their functionality in the form of Restful web services. This allows
any client application to call these web services via REST.
REST is used to build Web services that are lightweight, maintainable, and scalable in nature. A service which is built
on the REST architecture is called a RESTful service. The underlying protocol for REST is HTTP, which is the basic web
protocol. REST stands for REpresentational State Transfer
70 | P a g e
1. Resources – The first key element is the resource itself. Let assume that a web application on a server has records
of several employees. Let's assume the URL of the web application is http://www.server.com. Now in order to access
an employee record resource via REST, one can issue the command http://www.server.com/employee/1 - This
command tells the web server to please provide the details of the employee whose employee number is 1.
2. Request Verbs - These describe what you want to do with the resource. A browser issues a GET verb to instruct
the endpoint it wants to get data. However, there are many other verbs available including things like POST, PUT,
and DELETE. So in the case of the example http://www.server.com/employee/1 , the web browser is actually issuing
a GET Verb because it wants to get the details of the employee record.
3. Request Headers – These are additional instructions sent with the request. These might define the type of
response required or the authorization details.
4. Request Body - Data is sent with the request. Data is normally sent in the request when a POST request is made to
the REST web service. In a POST call, the client actually tells the web service that it wants to add a resource to the
server. Hence, the request body would have the details of the resource which is required to be added to the server.
5. Response Body – This is the main body of the response. So in our example, if we were to query the web server via
the request http://www.server.com/employee/1 , the web server might return an XML document with all the details
of the employee in the Response Body.
6. Response Status codes – These codes are the general codes which are returned along with the response from the
web server. An example is the code 200 which is normally returned if there is no error when returning a response to
the client.
Restful Methods
The below diagram shows mostly all the verbs (POST, GET, PUT, and DELETE) and an example of what they would
mean.
Let's assume that we have a RESTful web service is defined at the location. http://www.server.com/employee .
When the client makes any request to this web service, it can specify any of the normal HTTP verbs of GET, POST,
DELETE and PUT. Below is what would happen If the respective verbs were sent by the client.
POST – This would be used to create a new employee using the RESTful web service
GET - This would be used to get a list of all employee using the RESTful web service
PUT - This would be used to update all employee using the RESTful web service
DELETE - This would be used to delete all employee using the RESTful web service
===============================================================================================
What is REST ?
REST stands for REpresentational State Transfer.
It's the representation of the resource (eg : image/student/customer/invoice/bill....) using known data exchange
formats(text/xml/json) --which gets transferred between client & server .
REST is web standards based architecture and uses HTTP Protocol for data communication.
It revolves around resource where every component is a resource and a resource is accessed by a common interface
using HTTP standard methods. (ROA)
71 | P a g e
In REST architecture, a REST Server simply provides access to resources and REST client accesses and presents the
resources.
REST uses various representations to represent a resource like text, JSON and XML. Most popular light weight data
exchange format used in web services = JSON
HTTP Methods
Following well known HTTP methods are commonly used in REST based architecture.
A web service is a collection of open protocols and standards used for exchanging data between applications or
systems.
Software applications written in various programming languages and running on various platforms can use web
services to exchange data over computer networks like the Internet in a manner similar to inter-process
communication on a single computer.
This interoperability (e.g., between Java and Python, or Windows and Linux applications or java & .net ) is due to the
use of open standards.
Web services based on REST Architecture are known as RESTful web services.
These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually
defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP
Methods.
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Annotations
1. @PathVariable --- handles URL templates.
eg : URL -- http://host:port/test_web/products/10
Method of Controller
@GetMapping("/{pid}")
{...}
In the above URL , the path variable {pid} is mapped to an int . Therefore all of the URIs such as /products/1 or
/products/10 will map to the same method in the controller.
2. The @ResponseBody annotation is used to marshall(serialize) the return value into the HTTP response body.
Spring comes with converters that convert the Java object into a format understandable for a client.
3.The @RequestBody annotation, instead, unmarshalls the HTTP request body into a Java object injected in the
method.
72 | P a g e
-----------------------------------------------------------------------------------------------------------------------------------------
The RestTemplate is similar to other Spring templates such as JmsTemplate and JdbcTemplate in that Spring
eliminates a lot of boot strap code and thus makes your code much cleaner. When applications use the
RestTemplate they do not need to worry about HTTP connections, that is all encapsulated by the template. They also
get a range of APIs from the RestTemplate which correspond to the well know HTTP methods (GET, PUT, POST,
DELETE, HEAD, OPTIONS). These APIs are overloaded to cater for things like different ways of passing parameters to
the actual REST API.
--------------------------------------------------------------------------------------------------------------------------------------------
Create resful service provider project & then develop its client
For spring restful web service --actually only spring web mvc , hibernate validator & json jars are sufficient.
(get/post/put/delete)
5. For method=get
Can directly return either a resource eg : Person,BankAccount or Customer or still better is can return entire HTTP
response encapsulated in ResponseEntity<T>
What is org.springframework.http.ResponseEntity<T>
Constructors
Create a new ResponseEntity with the given body and status code, and no headers.
Create a new ResponseEntity with the given body and status code, and headers.
Return type of the method = either a resource or resource embedded in the ResponseEntity.
eg : @GetMapping(value="/cust/{id}")
73 | P a g e
1. In @PostMapping(value = "uri")
Return type of the method = either a resource or resource embedded in the ResponseEntity.
-------------------------------------------------------------------------------------------------------------------------------------
@RequestBody : If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP
request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that,
Spring will [behind the scenes] use HTTP Message converters to convert the HTTP request body into domain object
[deserialize request body to domain object], based on ACCEPT or Content-Type header present in request.
@ResponseBody : If a method is annotated with @ResponseBody, Spring will bind the return value to outgoing HTTP
response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return
value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP
header. As already mentioned, in Spring 4, no need to use this annotation.
@ResponseEntity is a real deal. It represents the entire HTTP response. Good thing about it is that you can control
anything that goes into it. You can specify status code, headers, and body. It comes with several constructors to carry
the information you want to sent in HTTP Response.
@PathVariable This annotation indicates that a method parameter should be bound to a URI template variable [the
one in '{}'].(binding between request handling method parametere & URI template variable)
MediaType : With @RequestMapping annotation, you can additionally, specify the MediaType to be produced or
consumed (using produces or consumes attributes) by that particular controller method, to further narrow down the
mapping.
-----------------------------------------------------------------------------------------------------------------------
URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping
method.
A URI Template is a URI-like string, containing one or more variable names. When you substitute
values for these variables, the template becomes a URI. The proposed RFC for URI Templates defines
{userId} contains the variable userId. Assigning the value fred to the variable yields http://
www.example.com/users/fred.
In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
74 | P a g e
public String findOwner(@PathVariable String ownerId, Model model) {
model.addAttribute("owner", owner);
return "displayOwner";
The URI Template " /owners/{ownerId}" specifies the variable name ownerId. When the controller
handles this request, the value of ownerId is set to the value found in the appropriate part of the URI.
For example, when a request comes in for /owners/abc, the value of ownerId is abc.
To process the @PathVariable annotation, Spring MVC needs to find the matching URI template
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
// some implementation
Or if the URI template variable name matches the method argument name you can omit that
detail. As long as your code is not compiled without debugging information, Spring MVC will match the method
argument name to the URI template variable name
A key difference between a traditional MVC controller and the RESTful web service controller is the way that the
HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the
data to HTML, typically a RESTful web service controller simply populates and returns a java object. The object data
will be written directly to the HTTP response as JSON/XML/Text
To do this, the @ResponseBody annotation on the ret type of the request handling method tells Spring MVC that it
does not need to render the java object through a server-side view layer, but that instead the java object returned is
the response body, and should be written out directly.
The java object must be converted to JSON. Thanks to Springs HTTP message converter support, you dont need to do
this conversion manually. Because Jackson Jar is on the classpath, SC can automatically convert the java object to
JSON & vice versa (using 2 annotations @ReponseBody & @RequestBody)
o.s.http.converter.HttpMessageConverter<T>
--Interface that specifies a converter that can convert from and to HTTP requests and responses.
Implementation classes
1. o.s.http.converter.xml.Jaxb2RootElementHttpMessageConverter
75 | P a g e
-- Implementation of HttpMessageConverter that can read and write XML using JAXB2.(Java architecture for XML
binding)
2. o.s.http.converter.json.
MappingJackson2HttpMessageConverter
--Implementation of HttpMessageConverter that can read and write JSON using Jackson 2.x's ObjectMapper class API
----------------
Annotations
Good news is @RestController = @Controller(at the class level) + @ResponseBody added on ret types of all request
handling methods
@RequestBody annotation must be still added on a method argument of request handling method , for un
marshaling(de serialization) though.
eg : URL -- http://host:port/test_web/products/10
Method of Controller
@GetMapping("/{pid}")
{...}
In the above URL , the path variable {pid} is mapped to an int . Therefore all of the URIs such as /products/1 or
/products/10 will map to the same method in the controller.
===============================================================================================
Optimistic Locking
When we talk about locking we are often referring to optimistic locking. The optimistic locking model
subscribes to the philosophy that there is a good chance that the transaction in which changes are made
to an entity will be the only one that actually changes the entity during that interval. This translates into
the decision to not acquire a lock on the entity until the change is actually made to the database, usually
When the data actually does get sent to the database to get updated at flush time or at the end of the
transaction, the entity lock is acquired and a check is made on the data in the database. The flushing
transaction must see whether any other transaction has committed a change to the entity in the
intervening time since this transaction read it in and changed it. If a change occurred, it means that the
flushing transaction has data that does not include those changes and should not write its own changes
to the database lest it overwrite the changes from the intervening transaction. At this stage, it must roll
76 | P a g e
==============================================================================================
OR
JPA 2 supports both optimistic locking and pessimistic locking. Locking is essential to avoid update collisions resulting
from simultaneous updates to the same data by two concurrent users. Locking in JPA) is always at the database
object level, i.e. each database object is locked separately.
Optimistic locking is applied on transaction commit. Any database object that has to be updated or deleted is
checked. An exception is thrown if it is found out that an update is being performed on an old version of a database
object, for which another update has already been committed by another transaction.
Optimistic locking should be the first choice for most applications, since compared to pessimistic locking it is easier
to use and more efficient.
In the rare cases in which update collision must be revealed earlier (before transaction commit) pessimistic locking
can be used. When using pessimistic locking, database objects are locked during the transaction and lock conflicts, if
they happen, are detected earlier.
Optismistic Locking
The initial version of a new entity object (when it is stored in the database for the first time) is 1. In every transaction
in which an entity object is modified its version number is automatically increased by one.
During commit , hibernate checks every database object that has to be updated or deleted, and compares the
version number of that object in the database to the version number of the in-memory object being updated. The
transaction fails and an OptimisticLockException is thrown if the version numbers do not match, indicating that the
object has been modified by another user (using another transaction) since it was retrieved by the current updater.
Pessimistic Locking
org.hibernate.Session API
Obtain the specified lock level upon the given object. This may be used to perform a version check (LockMode.READ)
or to upgrade to a pessimistic lock (LockMode.PESSIMISTIC_WRITE)
eg :
77 | P a g e
sf.getCurrentSession().lock(employee, LockMode.PESSIMISTIC_WRITE);
=============================================================================================
Design patterns
There are common problems faced by programmers all over.
Not a domain specific problem --asso with banking / insurance or manufacturing or pharma etc.
BUT if its a generic problem(eg : writing a web app , separating cross cutting concerns ) --then there are standard
solutions to these common problems -- these are nothing but the design patterns---best practises.
Design Patterns -- Started with Gang Of Four in 1994 --but being modified/enhanced since then.
Summary was
In a nut shell
Should u apply all of them -- NO ---nobody does that--you should only use those patterns which your appln demands.
eg : adapter
3. Behavioural -- best practises for communication between the objects (w/o any composition)
Pattern examples
1. singleton
2. Factory
In above case , SC is following factory pattern --provider of the rdymade spring beans (via ctx.getBean method)
2.5 Builder --
Use case --When there are too many parameters needed to be passed to a class constructor, instead use builder
pattern.
Structural Patterns
78 | P a g e
3. Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can
work together. The object that joins these unrelated interface is called an Adapter.
eg : Mobile charger works as an adapter between mobile charging socket and the wall socket.
1. We will have two classes – Volt (to measure voltage) and Socket (producing constant voltage of 230V).
2. Now build an adapter that can produce 3 volts, 12 volts and default 230 volts. So create an adapter interface with
these methods.
4. A tester
-------------------
Suppose we have an application with set of interfaces to use MySql/Oracle database and to generate different types
of reports, such as HTML report, PDF report etc.
So we will have different set of interfaces to work with different types of database. Now a client application can use
these interfaces to get the required database connection and generate reports.
But when the complexity increases or the interface behavior names are confusing, client application will find it
difficult to manage it.
So we can apply Facade design pattern here and provide a wrapper interface on top of the existing interface to help
client application.
eg :
3. Tester
----------------------
eg : AOP proxies.
--------------------
Template Method design pattern is used to create a method stub and deferring some of the steps of implementation
to the subclasses.
----------------
79 | P a g e
Allows us to achieve complete decoupling between the sender and the receiver.
With decoupling, the sender has no prior knowledge of the Receiver's interface.
The Command pattern also allows us to vary when and how a request is fulfilled. Thus : a Command pattern
provides us flexibility as well as extensibility.
eg :
2. Command i/f
5. tester
=========================================================================================
Contract
Format Support
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
Security
80 | P a g e
Rest inherits its security from underlying transport layer.
Bandwidth
SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub.
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use
various HTTP methods .
===========================================================================================
A method annotated with @Lookup tells Spring to return an instance of the method's return type when we invoke it.
Essentially, Spring will override our annotated method and use our method's return type and parameters as
arguments to BeanFactory#getBean.
Note also that @Lookup is the Java equivalent of the XML element lookup-method.
3. Using @Lookup
If we happen to decide to have a prototype Spring bean, then we are almost immediately faced with the problem of
how will our singleton Spring beans access these prototype Spring beans?
Now, Provider is certainly one way, though @Lookup is more versatile in some respects.
First, let's create a prototype bean that we will later inject into a singleton bean:
@Component
@Scope("prototype")
@Component
@Lookup
81 | P a g e
return null;
Using @Lookup, we can get an instance of SchoolNotification through our singleton bean:
@Test
assertEquals(first, second);
assertNotEquals(first.getNotification(), second.getNotification());
This is because Spring overrides the method with a call to beanFactory.getBean(StudentNotification.class), so we can
leave it empty.
Still more powerful, though, is that @Lookup allows us to inject a dependency procedurally, something that we
cannot do with Provider.
@Component
@Scope("prototype")
this.marks.add(mark);
82 | P a g e
return this.grader.grade(this.marks);
Now, it is dependent on some Spring context and also additional context that we will provide procedurally.
AD
We can then add a method to StudentServices that takes student data and persists it:
@Lookup
SchoolNotification notification
return notification.addMark(mark);
At runtime, Spring will implement the method in the same way, with a couple of additional tricks.First, note that it
can call a complex constructor as well as inject other Spring beans, allowing us to treat SchoolNotification a bit more
like a Spring-aware method.
Second, we can sometimes make the @Lookup-annotated method abstract, like the above example.
Using abstract is a bit nicer-looking than a stub, but we can only use it when we don't component-scan or @Bean-
manage the surrounding bean:
@Test
With this setup, we can add Spring dependencies as well as method dependencies to SchoolNotification.
4. Limitations
83 | P a g e
Despite @Lookup‘s versatility, there are a few notable limitations:
@Lookup-annotated methods, like getNotification, must be concrete when the surrounding class, like Student, is
component-scanned. This is because component scanning skips abstract beans.
@Lookup-annotated methods won't work at all when the surrounding class is @Bean-managed.
In those circumstances, if we need to inject a prototype bean into a singleton, we can look to Provider as an
alternative.
5. Conclusion
In this quick article, we learned how and when to use Spring's @Lookup annotation, including how to use it to inject
prototype-scoped beans into singleton beans and how to use it to inject dependencies procedurally.
===============================================================================================
eg : UsernamePasswordAuthenticationFilter.
OR If the incoming request contains the authorization header "Basic base-64 encoded credentials" , this request
goes through the chains of filters until it reaches BasicAuthenticationFilter.
Processes a HTTP request's Basic authorization header, putting the result into the SecurityContextHolder
2. AuthenticationToken is created based on User CredentialsFor the user login, once the authentication request
reaches the authentication filter, it will extract the username and password from the request payload. Spring
security will create an Authentication object based on the username and password.
UsernamePasswordAuthenticationToken authentication
Authentication Manager is the core for the Spring security authentication process.
ProviderManager has no idea about which auth provider will support the current authentication.
5. AuthenticationProviders
The AuthenticationProvider are responsible to process the request and perform a specific authentication. It provides
a mechanism for getting the user details with which we can perform authentication.
84 | P a g e
}
eg of implementation classes :
DaoAuthenticationProvider.
RememberMeAuthenticationProvider
LdapAuthenticationProvider
It depends upon
1. UserDetailsService
2. PasswordEncoder
DaoAuthenticationProvider needs UserDetailsService to get the user details stored in the database by username
package org.springframework.security.core.userdetails;
So you can configure this as a spring bean (@Bean) in your spring sec configuration file
During the authentication process, if the user authentication is successful, AuthenticationProvider will send a fully
initialized Authentication object back.
For failed authentication, AuthenticationException will be thrown, filter will send the response to the client HTTP
401
For failed authorization , filter will send the response to the client HTTP 403 (forbidden)
User credentials.
The last step in the successful authentication is setting up the authentication object in the SecurityContext. It wraps
the SecurityContext in the SecurityContextHolder.
9. The request is then delegated further to DispatcherServlet n continues with the usual flow.
===============================================================================================
85 | P a g e
JWT Details
Session-based Authentication & Token-based Authentication
For using any website, mobile app or desktop app , you need to create an account, then use it to login for accessing
features of the app : Authentication.
(refer : session-based-authentication.png)
As per the diag , when a user logs into a website, the Server will create a new Session for that user and store it (in
Memory or Database). Server also returns a SessionId for the Client to save it in Browser Cookie.
The Session on Server has an expiration time. After that time, this Session has expired and the user must re-login to
create another Session.
If the user has logged in and the Session has not expired yet, the Cookie (including SessionId) always goes with all
HTTP Request to Server. Server will compare this SessionId with stored Session to authenticate and return
corresponding Response.
The answer is we don’t have the only consumer as a browser (end user : client a person), we may have different
consumers of our services here.
So if you have a website which works well with thin client(browser client) & want to implement system for Mobile
(Native Apps) and use the same Web app. You can't authenticate users who use Native App using Session-based
Authentication because these native apps don’t support cookies. Or if you are implementing a REST server , every
REST request HAS TO be stateless , meaning you can't think of maintaining a Http Session in the back end. On the
other hand , you can't expect your front end app , to send you the credentials (username / password) along with
every request.
With this method, the user login state is encoded into a JSON Web Token (JWT) by the Server and sent to the Client
after successful authentication.
Instead of creating a Session, the Server generates a JWT from user login data and sends it to the Client. The Client
saves the JWT and then onwards sends this JWT along with every request , typically in a header to the server. The
Server will validate the JWT and return the Response.
For storing JWT on Client side, it depends on the platform you use:
IOS: Keychain
Android: SharedPreferences
Header
Payload
Signature
86 | P a g e
1. Header
eg :
"typ": "JWT",
"alg": "HS512"
– alg stands for ‘algorithm’ which is a hash algorithm for generating Token signature. Here HS256 is HMAC-
SHA256/512 – the algorithm which uses Secret Key.
2. Payload
"userId": "abcd123456",
"username": "rama",
"email": "[email protected]",
// standard fields
"iat": 1570238918,
"exp": 1570238992
In the JSON object above, we store 3 user fields: userId, username, email. You can save any field you want.
3. Signature
In Java code :
Base64 is a binary-to-text encoding scheme. It represents binary data in a printable ASCII string format by translating
it into a radix-64 representation.
87 | P a g e
The basic encoder keeps things simple and encodes the input as is, without any line separation.
The output is mapped to a set of characters in A-Za-z0-9+/ character set, and the decoder rejects any character
outside of this set.
eg : In Java
In Javascript
- Next, makes a hash of the data using Hash algorithm (defined at Header) with a secret string.
After having Header, Payload, Signature, combines them into JWT standard structure: header.payload.signature.
JWT does not hide, obscure, secure data at all. You can see that the process of generating JWT (Header, Payload,
Signature) only encode & hash data, not encrypt data.
The purpose of JWT is to prove that the data is generated by an authentic source.
So, what if there is a Man-in-the-middle attack that can get JWT, then decode user information?
Yes, that is possible, so always make sure that your application has the HTTPS encryption.
For creating a JWT , we use a Secret string to create Signature. This Secret string is unique for every Application and
must be stored securely in the server side.
When receiving JWT from Client, the Server get the Signature, verify that the Signature is correctly hashed by the
same algorithm and Secret string as above. If it matches the Server’s signature, the JWT is valid.
Separating cross-cutting concerns(=repeatative tasks) from the business logic/ request handling /persistence
IMPORTANT
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Dependency
Injection helps you decouple your application objects from each other(eg : Controller separate from Service or DAO
layers) and AOP helps you decouple cross-cutting concerns from the objects that they affect.(eg : transactional code
or security related code can be kept separate from B.L or exception handling code from request handling method)
eg scenario --
88 | P a g e
Think of a situation Your manager tells you to do your normal development work(eg - write stock trading appln) +
write down everything you do and how long it takes you.
A better situation would be you do your normal work, but another person observes what youre doing and records it
and measures how long it took.
Even better would be if you were totally unaware of that other person and that other person was able to also
observe and record , not just yours but any other peoples work and time.
That's separation of responsibilities. --- This is what spring offers you through AOP.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
Struts 2 -- interceptors
Servlet -- filters.
RMI -- stubs
Hibernate --- proxy (hib frmwork -- lazy --- load or any--many associations --rets typically un-inited proxy/proxies)
One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework.
The functionalities that span multiple points of an application are called cross-cutting concerns.
Its better for application objects(service layer/controller/rest controller/DAO) to focus on the business domain
problems that they are designed for and leave certain ASPECTS to be handled by someone else.
Job of AOP framework is --- Separating these cross-cutting concerns(repeatative tasks) from the core business logic
Spring AOP module provides interceptors to intercept an application, for example, when a method is executed, you
can add extra functionality before or after the method execution.
----------------------------------
1.Advice : Action(=cross cutting concern) to take either before/after or around the method (req handling logic ,OR
B.L OR data access logic) execution. eg: transactional logic(begin tx,commit,rollback,session closing)
89 | P a g e
eg : logging. It is sure that each object will be using the logging framework to log the event happenings , by calling
the log methods. So, each object will have its own code for logging. i.e the logging functionality requirement is
spread across multiple objects (call this as Cross cutting Concern, since it cuts across multiple objects). Wont it be
nice to have some mechanism to automatically execute the logging code, before executing the methods of several
objects?
2. Join Point : Place in application WHERE advice should be applied.(i.e which B.L methods should be advised)
eg :
advice logic{....}
5. Aspect : class representing advisor(advice logic + point cut definition)-- @Asepct -- class level annotation.
6. Target : Application Object containing Core domain logic.(To which advice gets applied at specified join points) --
supplied by Prog
7. Proxy : Object created after applying advice to the target object(created by SC dynamically by implementing
typically service layer i/f) ---consists of cross cutting concern(repeatative jobs , eg : tx management,security, exc
handling)
(3 ways --- compile time, class loading time or spring supported --dynamic --method exec time or run time)
@Before : This advice (cross cutting concern) logic gets Executed only before B.L method execution.
Regarding pointcuts
Sometimes we have to use same Pointcut expression at multiple places, we can create an empty method with
@Pointcut annotation and then use it as expression in advices.
@Before("execution (* com.app.bank.*.*(..))")
@Pointcut("execution (* com.app.bank.*.*(double))")
@Pointcut("execution (* com.app.service.*.add*(..))")
90 | P a g e
// point cut signature -- empty method .
1. @Before(value = "test()")
2. @Pointcut("within(com.app.service.*)")
@Before("allMethodsPointcut()")
4. //Advice arguments, will be applied to bean methods with single String argument
@Before("args(name)")
@Pointcut("within(com.app.service.*)")
7.@Pointcut("execution(* com.app.core.Student.getName(..))")
------------------------------------------
4. To Enable the use of the @AspectJ style of Spring AOP & automatic proxy generation, add <aop:aspectj-
autoproxy/>
@PointCut("execution (* com.aop.service.Account.add*(..))")
91 | P a g e
public void test() {}
OR
@Before("execution (* com.aop.service.Account.add*(..))")
eg : @Before("execution (* com.app.bank.*.*(..))")
having ANY ret type, from ANY class from pkg -- com.app.bank
Any advice method may declare as its first parameter, a parameter of type org.aspectj.lang.JoinPoint (In around
advice this is replaced by ProceedingJoinPoint, which is a subclass of JoinPoint.)
===============================================================================================
An HTTP multipart request is an HTTP request that HTTP clients construct to send files and data over to an HTTP
Server. It is commonly used by browsers and HTTP clients to upload files to the server.
92 | P a g e
The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for
copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at
the end of request processing.
Stpes
1. To upload a file to a server side folder add the property (any property name)
file.upload.location=images
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=15MB
2. File upload
OR
Other emp details are already stored in DB. image path has to be stored in the table n image should be uploaded in
the "images" folder.
resp : Emp DTO (with image file name set) or Simply ApiResponse
eg : Method : POST
http://localhost:8080/api/employees/{empId}/images
1. Create total path , using folder location ,file separator , image file's original file name
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
Copies all bytes from an input stream to a file returning no of bytes copied.
3. Save image path in Emp entity (to trigger update query) --setter
4. Return Emp DTO to the caller.(service --> controller --> JSON representation to clnt)
93 | P a g e
5. Test it with postman
i/p : emp id
Steps
3.1 In Controller
Method = GET
emp's getter
Method :
Reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O
error, or other runtime exception, is thrown.
Method : GET
http://localhost:8080/api/employees/{empId}/image
==========================================================================================
94 | P a g e