Advance Java
Advance Java
MCA
SEMESTER - I (CBCS)
ADVANCE JAVA
SUBJECT CODE: MCA12
© UNIVERSITY OF MUMBAI
: Rani Podichetty
Assistant Professor
VK. B college of Arts and Commerce, Mumbai
: Sneha Khajane
Assistant Professor
Ghanshyamdas saraf college, Mumbai
: Pinky Rane
Assistant Professor
New horizon college of commerce, Mumbai.
: Vaibhav Sakpal
Assistant Professor
Wada college of management and science00042
Published by : Director,
Institute of Distance and Open Learning,
University of Mumbai,
Vidyanagari,Mumbai - 400 098.
ii
CONTENTS
Chapter No. Title Page No.
Unit I
1. Collection and Generic ......................................................................................1
2. Lambda Expressions.........................................................................................26
Unit II
3. JSP Architecture...............................................................................................40
4. Introduction to Bean.........................................................................................52
Unit III
5. Introduction to Spring .....................................................................................59
Unit IV
7. Spring and AOP................................................................................................92
Unit V
Unit VI
iii
F.Y. MCA
SEMESTER - I (CBCS)
ADVANCE JAVA
SYLLABUS
03 Spring Frameworks: 6
Introduction to Spring Framework,POJO Programming Model, Lightweight
Containers(Spring IOC container, Configuration MetaData, Configuring and
using the Container) Dependency Injection with Spring- Setter Injection,
Constructor Injection, Circular Dependency, Overriding Bean, Auto Wiring
Bean Looksup, Spring Manage Beans)
Self learning topics Bean Definition Profiles
04 Spring and AOP 5
AspectOriented Programming with Spring, Types of advices, Defining Point
Cut Designator,Annotations.
Self learning topics AspectJ
05 JDBC Data Access with Spring 6
Managing JDBC Connection, Configuring Data Source to obtain JDBC
Connection, Data Access operations with JdbcTemplate and Spring, RDBMS
operation classes , Modelling JDBC Operations as Java Objects
Self learning topics JDBC Architecture and basic JDBC Program using DML
operation
06 Getting Started with Spring Boot 6
Spring Boot and Database, Spring Boot Web Application Development,
Spring Boot RESTful WebServices.
Self learning topics Understanding Transaction Management in Spring
iv
Chapter 1: Collection and Generics
Module 1
1
COLLECTION AND GENERICS
Unit Structure
1.0 Objectives
1.1 Introduction to Generics
1.1.1 Advantages of Generics
1.1.2 Generic Classes
1.1.3 Generic Methods
1.1.4 Bounded Type Parameters
1.2 Wildcards
1.2.1 Types of Wildcards
1.3 Introduction to Java Collections
1.3.1 Java Collection Framework
1.3.2 Java Collection Hierarchy
1.3.3 Advantages of Collection
1.3.4 Framework Basic and Bulk Operations on Java Collection
1.4 List
1.4.1 Methods of List Interface
1.4.2 How to create List - ArrayList and LinkedList
1.4.3 Iterating through the List
1.5 Set
1.5.1 Methods of Set Interface
1.5.2 HashSet Class
1.5.3 TreeSet Class
1.6 Map
1.6.1 Methods of Map Interface
1.6.2 HashMap Class
1.6.2 LinkedHashMap Class
1.6.3 TreeMap Class
1.7 Let Us Sum Up
1.8 List of References
1.9 Chapter End Exercises
1
ADVANCE JAVA
1.0 Objectives
After going through this chapter, you will be able to:
• Understand the Collections API
• Learn what is generics and how to write Generic Classes and Methods
• Perform basic operations on Collection
• Learn what are wildcard characters and types of wildcards
• Understand List, Set and Maps
1.1 Introduction to Generics
The Java Generics was added to JDK 1.5 which allowed programming
generically. It allows creating classes and methods that work in the same way on
different types of objects while providing type-safety right at the compile-time It
makes the code stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic.
Now generics force the java programmer to store a specific type of objects.
1.1.1 ADVANTAGE OF GENERICS
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety
We can hold only a single type of objects in generics. It doesn’t allow to
store other objects. Without Generics, we can store any type of objects.
Example:
List list = new ArrayList();
list.add(10); //Storing an int value in list
list.add("10"); //Storing a String value in list
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
2) Type casting is not required
There is no need to typecast the object. Before Generics, we need to type cast.
Example:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
After Generics, we don't need to typecast the object.
2
Chapter 1: Collection and Generics
Example:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: Type checking is done at compile time so errors
will not occur at runtime.
Example:
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
1.1.2 GENERIC CLASSES
Generics is not only limited to collection. It is also possible to use Generics with
classes. A generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section.
The type parameter section of a generic class can have one or more type parameters
separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.
Example: Program that demonstrates Generic Classes
public class Shape<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Shape<Integer> intShape = new Shape<Integer>();
Shape<String> strShape = new Box<String>();
intShape.add(new Integer(25));
strShape.add(new String("Generic Classes"));
System.out.printf("Integer Value :%d\n\n", intShape.get());
System.out.printf("String Value :%s\n", strShape.get());
}
}
3
ADVANCE JAVA
Output
Integer Value :25
String Value : Generic Classes
In this program, Box is coded as a Generic Class. Technically, Box is a parametric
class and T is the type parameter. T serves as a placeholder for holding any type of
Object. We can use the above class by substituting any kind of object for the
placeholder T.
1.1.3 GENERIC METHODS
A generic method declaration can have arguments of different types. Based on the
types of the arguments passed to the generic method, the compiler handles each
method call appropriately. Unlike a Generic Class, a generic method containing
different parameters affects only that method. alone. Hence, a class which is not
generic can contain generic and non-generic methods.
Rules for defining Generic Methods
• All generic method declarations have a type parameter section delimited by
angle brackets (< and >) that precedes the method's return type < T >
• Each type parameter section contains one or more type parameters
separated by commas. A type parameter is an identifier that specifies a
generic type name.
• The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments.
• A generic method's body is declared like that of any other method.
• Note that type parameters can represent only reference types, not primitive
types (like int, double and char).
Example 1: Program that prints the type of data passed using a single Generic
method
public class GenericMethodsEx1
{ // generic method print
public static <T> void print(T t)
{ System.out.println(t.getClass().getName());
}
public static void main(String args[]) {
GenericMethodsEx1.print(“Hello World”);
GenericMethodsEx1.print(100);
}
}
4
Chapter 1: Collection and Generics
Output;
java.lang.String
java.lang.Integer
In this program, the static method print has a return type void and it takes a single
parameter called T. T stands for parametric type which can be substituted with any
of the Java types by a client application.
Example 2: Program that prints an array of different type using a single
Generic method
public class GenericMethodEx2 {
// generic method printArray
public static < T > void printArray( E[] i )
{
// Display array elements
for(T element : i) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(intArray); // pass an Integer array
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\nArray characterArray contains:");
printArray(charArray); // pass a Character array
}
}
5
ADVANCE JAVA
Output
Array integerArray contains:
12345
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
HELLO
In this program, the static method printArray has a return type void and it takes a
single parameter called T. T stands for parametric type which can be substituted
with any of the Java types by a client application. The main method passes arrays
with different types and the single generic method is used to print all of the array
elements.
1.1.4 BOUNDED TYPE PARAMETERS
Sometimes it is required to restrict the kinds of types that are allowed to be passed
to a type parameter. Example, a method that operates on numbers might only want
to accept instances of Number or its subclasses. In such cases, bounded type
parameters can be used.
To declare a bounded type parameter, list the type parameter's name, followed by
the extends keyword, followed by its upper bound like below:
class Example <T extends Number>
Example: Program that calculates the average of numbers either integer or
double
package p1;
public class Test<T extends Number> {
T[] numArr;
Test(T[] numArr) {
this.numArr = numArr;
}
public double getAvg() {
double sum = 0.0;
for (int i = 0; i < numArr.length; i++) {
sum += numArr[i].doubleValue();
}
double avg = sum / numArr.length;
return avg;
}
public static void main(String[] args) {
6
Chapter 1: Collection and Generics
Output
Average of Integers = 14.0
Average of Double =2.5
1.2 WILDCARD CHARACTER
• The question mark (?) is known as the wildcard in generic programming . It
represents an unknown type.
• The wildcard can be used in a variety of situations such as the type of a
parameter, field, or local variable; sometimes as a return type.
• Unlike arrays, different instantiations of a generic type are not compatible
with each other, not even explicitly. This incompatibility may be softened by
the wildcard if ? is used as an actual type parameter.
1.2.1 TYPES OF WILDCARDS
There are three types of wildcards: They are:
1. UPPER BOUNDED WILDCARDS
➢ These wildcards can be used when you want to relax the restrictions on a
variable.
➢ For example, say you want to write a method that works on List < Integer >,
List<Double > and List < Number > , you can do this using an upper bounded
wildcard.
➢ To declare an upper-bounded wildcard, use the wildcard character (‘?’),
followed by the extends keyword, followed by its upper bound
Ex: public static void add(List<? extends Number> list)
7
ADVANCE JAVA
Output
Total sum is:22.0
Total sum is:15.299999999999999
Here, the sum method is used to calculate the sum of both Integer list and Double
list elements as it accepts list as a parameter whse upper bound is Number.
8
Chapter 1: Collection and Generics
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
Here, the print method is used to calculate the print both Integer list and Number
list elements as it accepts list as a parameter whse lower bound is Integer.
3. UNBOUNDED WILDCARDS
The unbounded wildcard type is specified using the wildcard character (?), for
example, List<?>. This is called a list of unknown type.
9
ADVANCE JAVA
Output
1
2
3
one
two
three
Here, li and ls are Integer and String lists created from Arrays and both lists are
printed using the generic method printList.
10
Chapter 1: Collection and Generics
The Collection interface is the root of the collection hierarchy and is implemented
by all the classes in the collection framework.
11
ADVANCE JAVA
12
Chapter 1: Collection and Generics
The Collection Interface also contains methods that performs operations on entire
collections which are also called as bulk operations.
Methods Description
boolean containsAll(Collection<?> c) Used to check if this collection
contains all the elements in the
invoked collection.
boolean addAll(Collection<? extends E> Used to insert the specified
c) collection elements in the invoking
collection.
boolean removeAll(Collection<?> c) Used to delete all the elements of
the specified collection from the
invoking collection.
boolean retainAll(Collection<?> c) Used to delete all the elements of
invoking collection except the
specified collection.
void clear() Removes all the elements from the
collection.
Iterator interface
It provides the facility of iterating the elements in a collection.
Method Description
LIST
List in Java provides the facility to maintain the ordered collection. It contains the
index-based methods to insert, update, delete and search the elements. It can have
the duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection
interface. It is a factory of ListIterator interface. Through the ListIterator, we can
iterate the list in forward and backward directions.
13
ADVANCE JAVA
Method Description
void add(int index, E It is used to insert the specified element at the
element) specified position in a list.
It is used to append the specified element at the end
boolean add(E e)
of a list.
It is used to remove all of the elements from this
void clear()
list.
It is used to compare the specified object with the
boolean equals(Object o)
elements of a list.
int hashcode() It is used to return the hash code value for a list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
It is used to return the index in this list of the last
int lastIndexOf(Object
occurrence of the specified element, or -1 if the list
o)
does not contain this element.
14
Chapter 1: Collection and Generics
Output:
[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]
15
ADVANCE JAVA
LinkedList
LinkedList is a class which is implemented in the collection framework which
inherently implements the linked list data structure. It is a linear data structure
where the elements are not stored in contiguous locations and every element is a
separate object with a data part and address part. The elements are linked using
pointers and addresses. Each element is known as a node. Linked List permits
insertion and deletion of nodes at any point in the list in constant time, but do not
allow random access. It permits all elements including null.
Example: Program that demonstrates List using LinkedList class
import java.io.*;
import java.util.*;
class LinkedListDemo {
public static void main(String[] args)
{
// Size of the LinkedList
int n = 5;
// Printing elements
System.out.println(ll);
16
Chapter 1: Collection and Generics
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
1.4.3 ITERATING THROUGH THE LIST
There are multiple ways to iterate through the List. The most famous ways are by
using the basic for loop in combination with a get() method to get the element at a
specific index and the advanced for loop.
Example: Program that iterates through an ArrayList
import java.util.*;
public class ArrayListIteration {
public static void main(String args[])
{
List<String> al= new ArrayList<String>();
al.add("Ann");
al.add("Bill");
al.add(“Cathy”);
System.out.println();
Output:
Ann Bill Cathy
Ann Bill Cathy
17
ADVANCE JAVA
1.5 Set
The set extends the Collection interface is an unordered collection of objects in
which duplicate values cannot be stored. This interface is present in the java.util
package and contains the methods inherited from the Collection interface.
The most popular classes which implement the Set interface are HashSet and
TreeSet.
The List interface is declared as:
public interface Set extends Collection
1.5.1 METHODS OF SET INTERFACE
Method Description
add(element) It is used to add a specific element to the set.
It is used to append all of the elements from the
addAll(collection)
mentioned collection to the existing set
It is used to remove all the elements from the set but
clear() not delete the set. The reference for the set still
exists.
It is used to check whether a specific element is
contains(element)
present in the Set or not.
isEmpty() It is used to check whether the set is empty or not.
It is used to return the of the set. The
iterator() elements from the set are returned in a random
order.
18
Chapter 1: Collection and Generics
19
ADVANCE JAVA
class TreeSetDemo {
public static void main(String[] args)
{
Set<String> ts = new TreeSet<String>();
Output:
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa
20
Chapter 1: Collection and Generics
1.6 Maps
The Map interface present in java.util package represents a mapping between a key
and a value. A map contains unique keys and each key can map to at most one
value. Some implementations allow null key and null value like the HashMap and
LinkedHashMap, but some do not like the TreeMap. The order of a map depends
on the specific implementations. For example, TreeMap and LinkedHashMap have
predictable order, while HashMap does not.
The Map interface is not a subtype of the Collection interface. Therefore, it behaves
a bit differently from the rest of the collection types.
The classes which implement the Map interface are HashMap, LinkedHashMap
and TreeMap.
1.6.1 METHODS OF MAP INTERFACE
Method Description
This method is used to clear and remove all of the
clear() elements or mappings from a specified Map
collection.
This method is used to check for equality between
two maps. It verifies whether the elements of one
equals(Object)
map passed as a parameter is equal to the elements of
this map or not.
This method is used to retrieve or fetch the value
mapped by a particular key mentioned in the
get(Object)
parameter. It returns NULL when the map contains
no such mapping for the key.
This method is used to generate a hashCode for the
hashCode()
given map containing key and values.
This method is used to check if a map is having any
isEmpty() entry for key and value pairs. If no mapping exists,
then this returns true.
This method is used to clear and remove all of the
clear() elements or mappings from a specified Map
collection.
1.6.2 HASHMAP
HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it
will replace the element of the corresponding key. It is easy to perform operations
21
ADVANCE JAVA
using the key index like updation, deletion, etc. HashMap class is found in the
java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for
value.
Output:
vaibhav 20
vishal 10
sachin 30
1.6.3 LINKEDHASHMAP
LinkedHashMap is just like HashMap with an additional feature of maintaining the
order of elements inserted into it. HashMap provided the advantage of quick
insertion, search and deletion but it never maintained the track and order of
insertion which the LinkedHashMap provides where the elements can be accessed
in their insertion order.
22
Chapter 1: Collection and Generics
map.put("Angel", 10);
map.put("Liza", 30);
map.put("Steve", 20);
Output:
Angel 10
Liza 30
Steve 20
1.6.4 TREEMAP
The TreeMap in Java is used to implement Map interface and NavigableMap along
with the Abstract Class. It provides an efficient means of storing key-value pairs in
sorted order. TreeMap contains only unique elements and cannot have a null key
but can have multiple null values.
TreeMap is non synchronized and maintains ascending order.
Example: Program that demonstrates TreeMap implementation
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
23
ADVANCE JAVA
map.put(100, "Angel");
map.put(101, "Chris");
map.put(103, "Bill");
map.put(102, "Steve");
for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Output:
100 Angel
101 Chris
102 Steve
103 Bill
24
Chapter 1: Collection and Generics
• List contains the index-based methods to insert, update, delete, and search
the elements. It can have duplicate elements also.
• The Set follows the unordered way and can store only unique elements.
• Map represents a mapping between a key and a value. Each key is linked to
a specific value.
1.8 List of References
1. Java 8 Programming, BlackBook, DreamTech Press, Edition 2015
2. Core Java 8 for Beginners, Sharanam Shah, Vaishali Shah, Third Edition,
SPD
Web References
1. https://www.geeksforgeeks.org
2. https://www.javatpoint.com
3. https://www.tutorialspoint.com
25
ADVANCE JAVA
Module 1
2
LAMBDA EXPRESSIONS
Unit Structure
2.0 Objectives
2.1 Introduction
2.1.1 What is Lambda Expression?
2.1.2 Why to use Lambda Expression?
2.1.3 Syntax of Lambda Expression
2.1.4 Where can Lambda Expressions be used?
2.2 Lambda Type Inference
2.3 Lambda Parameters
2.4 Lambda Function Body
2.5 Returning a Value from a Lambda Expression
2.6 Lambdas as Objects
2.7 Lambdas in Collections
2.8 Let us Sum Up
2.9 List of References
2.10 Chapter End Exercises
2.0 Objectives
After going through this chapter, you will be able to:
• Understand what are Lambda Expressions and how to write lambda
expressions
• State the advantages of using lambda expressions
• Explain the different ways parameters can be passed in a Lambda
Expressions
• Understand target type inferencing
• Simplify programs and reduce code length using Lambda Expressions
2.1 Introduction
Lambda expressions is a new and significant feature of Java which was introduced
in Java SE 8 and became very popular as it simplifies code development. It provides
a very clear and concise way to represent single method interfaces using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection. Lambda Expressions is Java’s first step towards functional
26
Chapter 2: Lambda Expressions
Output:
Area of square = 100
Here you can note that we are rewriting the method declaration code public void
area() written in the interface again in the anonymous inner class. This repetitive
code can be eliminated if we use Lambda Expressions.
27
ADVANCE JAVA
Now, we can convert the above method into a lambda expression by removing the
public access specifier, return type declaration, such as void, and the name of
method ‘display’.
28
Chapter 2: Lambda Expressions
() -> {
System.out.println(“Hello World”);
}
Output:
Area of square = 100
Here, you can observe that we have not written the method declaration public void
area() present in the interface while implementing it in the class using lambda
expression. Thus reducing repetitive code.
2.1.4 WHERE CAN LAMBDA EXPRESSIONS BE USED?
Lambda Expressions can be written in any context that has a target datatype. The
contexts that have target type are:
29
ADVANCE JAVA
interface Operation{
int add(int a,int b);
}
Output:
30
Here, the compiler can infer that a and b must be int because the lambda
expression is assigned to a Operation reference variable.
2.3 LAMBDA PARAMETERS
30
Chapter 2: Lambda Expressions
//Functional Interface
interface MyFunctionalInterface {
//A method with no parameter
public void say(); }
Output
Hello
• When there is a single parameter, if its type is inferred, it is not mandatory to
use parentheses.
For Example:
(str) -> { System.out.println(“Single Parameter Lambda Expression” + str); }
Example: Program demonstrating Lambda Expression with Single Parameter
//Functional Interface
interface MyFunctionalInterface {
//A method with single parameter
public void say(String str);
}
public class SingleParamLambda {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface msg = (str) -> {
System.out.println(str);
};
msg.say("Hello World");
}
}
31
ADVANCE JAVA
Output
Hello World
• When there are multiple parameters, they are enclosed in parentheses and
separated by commas.
For Example:
(str1, str2) ->{
System.out.println(“Multiple Parameter Lambda Expression ” +str1+ str2);
}
Example: Program demonstrating Lambda Expression with Multiple Parameters
//Functional Interface
interface MyFunctionalInterface {
//A method with single parameter
public void say(String str1, String str2);
}
public class SingleParamLambda {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface msg = (str1, str2) -> {
System.out.println(str1 +" "+ str2);
};
msg.say("Hello", "Java");
}
}
Output
Hello Java
2.4 LAMBDA FUNCTION BODY
• The body of a lambda expression, and thus the body of the function / method
it represents, is specified to the right of the -> in the lambda declaration.
() -> {
System.out.println("Hello");
};
• A lambda Expression body can have zero to any number of statements.
• Statements should be enclosed in curly braces.
• If there is only one statement, curly brace is not needed.
• When there is more than one statement in body then these must be enclosed
in curly brackets and the return type of the anonymous function is the same
as the type of the value returned within the code block or void if nothing is
returned.
32
Chapter 2: Lambda Expressions
33
ADVANCE JAVA
30
70
34
Chapter 2: Lambda Expressions
Elements of the ArrayList before sorting : [205, 102, 98, 275, 203]
Elements of the ArrayList after sorting : [275, 205, 203, 102, 98]
2.7 MORE EXAMPLE PROGRAMS USING LAMBDA EXPRESSIONS
1. Write a program using Lambda expression to calculate average of 3 numbers.
interface Operation {
double average(int a, int b, int c);
}
class Calculate {
public static void main(String args[]) {
Operation opr = (a, b, c) -> {
double sum = a + b + c;
return (sum / 3);
};
System.out.println(opr.average(10, 20, 5));
}
}
Output
11.666666666666666
2. Write a program to store integer values 1 to 5 in an ArrayList and print all
numbers,even numbers and odd numbers using Lambda expression.
import java.util.ArrayList;
class Test
{
public static void main(String args[])
{
// Creating an ArrayList with elements 1,2,3,4,5
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
arrL.add(5);
35
ADVANCE JAVA
}
);
Output
Displaying all numbers
1
2
3
4
5
Displaying even numbers
2
4
Displaying odd numbers
1
3
5
3. Write a program using Lambda Expressions to calculate the area of circle
with radius 5.
interface Area {
double calculate(int r);
}
class AreaofCircle {
public static void main(String args[]) {
Area a = (r) -> {
double area = 3.142 * r * r;
return (area);
};
System.out.println(a.calculate(5));
}
}
Output:
Area of circle=78.55
36
Chapter 2: Lambda Expressions
37
ADVANCE JAVA
}
}
Output:
Before Sorting the student data:
Student[ Name:John Age: 22 Id: 1001]
Student[ Name:Steve Age: 19 Id: 1003]
Student[ Name:Kevin Age: 23 Id: 1005]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Chris Age: 18 Id: 1111]
After Sorting the student data by Age:
Student[ Name:Chris Age: 18 Id: 1111]
Student[ Name:Steve Age: 19 Id: 1003]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:John Age: 22 Id: 1001]
Student[ Name:Kevin Age: 23 Id: 1005]
After Sorting the student data by Name:
Student[ Name:Chris Age: 18 Id: 1111]
Student[ Name:John Age: 22 Id: 1001]
Student[ Name:Kevin Age: 23 Id: 1005]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Steve Age: 19 Id: 1003]
38
Chapter 2: Lambda Expressions
❖❖❖❖❖
39
ADVANCE JAVA
Module2
3
JSP ARCHITECTURE, JSP BUILDING BLOCKS,
SCRIPTING TAGS, IMPLICIT OBJECT
INTRODUCTION TO JSP STANDARD TAG
LIBRARY (JSTL) AND JSTL TAGS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Problems of Servlets
3.2.1 Static Content
3.2.2 For each client request you have to write service()
3.2.3 Any modification made in static content the Servlets need to be
recompiled and redeployed.
3.3 Servlet Life Cycle
3.3. a Diagram
3.4 JSP Architecture
3.4.a Diagram
3.5 JSP building blocks
3.5. a Scriptlet tags
3.5. b Declaration tags
3.5. c Expression tags
3.6 Scripting Tags
3.6.a Comments
3.6.b Directives
3.6.c Declaration
3.6.d JSP scriptlet tags
3.6.e Expression
3.7 Implicit Objects
3.7.1 Out
3.7.2 request
3.7.3 response
3.7.4 config
3.7.5 application
3.7.6 session
3.7.7 page context
3.7.8 page
3.7.9 Exception
3.8 Introduction to JSP Standard Tag Library (JSTL) and JSTL Tags.
3.9 Summary
3.10 Reference for further reading
40
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
3.0 Objectives
The primary objectives of learning this course will help the students to understand
the basic concepts of Servlets, deployment of JSP, development of dynamic web
pages, uses of various implicit objects and JSTL predefined library.
3.1 Introduction
JSP (Java Server Pages) it is an extension or we can say add- on of Servlets
technology. JSP provides more functionality as compared to Servlets. It is
basically used to develop web applications. It is nothing but similar to Servlets
which works on processing the request and generating the response objects, it is
the same applies to JSP applications also. In Servlets we accept the request from
the client, we process the request and then the Servlets generate the response. The
same way we can implement the process of accepting the request and generating
the response using JSP in much more simpler way without overriding much more
methods as of Servlets. JSP comprises of HTML and JSP tags that is why it said
that JSP pages are easier to maintain than Servlets because it gives you a separate
space for designing and development of web applications.
Before starting with JSP we should have a rough idea about the Servlets and how
it works and the reason behind the use of JSP over Servlets technology. It means
that we can say how JSP overcomes the drawbacks of Servlets. Servlets are
actually the base of web applications and it has its own life cycle which gets
executed each time the request is made from the client side. Servlets are some
time also known as server-side coding that is (Business logic).
Diagram a) How Servlets works using GetRequest() method
41
ADVANCE JAVA
2) For each client request you have to write service() method :- In Servlets
for every new request you have to write the service() method which was
causing more processing time at the server end. In short to handle each
request in Servlets, we need to have service() for each upcoming request
from the client. So this creates a burden on the server-side to handle too
much of request and its service() method for each request.
Solution using JSP: - So the solution for it is there should no pressure of writing
the code of service() method for each request made by the client. The request
can be processed without taking much more time for processing the request. It
means that the request should get processed directly without its service() method
using JSP.
Note: Before starting with JSP just go through the Servlets life cycles which
will help you further to understand JSP in an easy way.
42
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
d) After calling the service() method it will starts processing the request of the
client and the execution of business logic of service() method gets invoked.
Note: - For every new request the service () method is called each time by
the Servlets.
e) After processing the request and the execution of service() method , the web
container will starts destroying or you can say starts releasing the
resources used by the Servlets for processing the request and invoking the
service() method.
f) The last stage is to call or invoke the destroy() method of the Servlets and
its object.
43
ADVANCE JAVA
Before starting JSP you should know about the use of HTML tags. It is a
Hypertext Markup Language which helps the programmer to describe or you can
say design the structure of web pages. So java is embedded in html tags to create
dynamic web pages called as JSP.
JSP: - it is a technology that is supported to develop dynamic web pages using
Java code, Html tags and some scripting tags. The JSP pages follow these phases:
1) Translation of JSP page.
2) Compilation of JSP page
3) Classloading
4) Instantiation
5) Initialization
6) Request Processing( web container invokes jspService() method)
7) Destroy (web container invokes jspDestroy() method)
44
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
Note: The life cycle methods of JSP are: jspInit(), jspService(), jspDestroy
S().
Step 1: With the help of JSP translator the JSP page is first translated into
Servlets.
Step 2: The JSP translator is a part of web server which handles the translation of
JSP page into Servlets.
Step 3: After that the Servlet page is compiled by the compiler and .class file is
created which is binary file.
Step 4: All processes that take place in Servlets are performed same in JSL later
that is initialization and sending response to the browser and then at the end
invoking destroy () method.
Diagram 3.4.a Life cycle of JSP Page:
45
ADVANCE JAVA
will process any code written within the pair of the <% %> tags, and any other
text within the Jsp page will be treated as a html code. In short the sciptlet tag is
used to execute the java code in JSP.
Syntax: -<% Java code %>
Example:
<html>
<body>
<% out.print(“Welcome to JSP”) %>
</body>
</html>
<html>
<body>
<%=” JSP based String” %.>
</body>
</html>
3.5. c. Declaration Tag:- It is used to define or you can say declare methods and
variables in JSP. The code written inside the jsp declaration tag is placed outside
the service() method.
Syntax: <%! Declaration %>
46
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
3.6.1 Comments
Comments are used to write some text or statements that are ignored by the JSP
compiler. It is very useful when someone wants to remember some logic or
information in future.
Syntax: <%-- A JSP COMMENT--%>
3.6.2 Directives
It is used to give some specific instructions to web container when the jsp page is
translated. It has three subcategories:
• Page:<%@ page...>
• Include:<%@ include...%>
• Taglib:<%@ taglib....%>
3.6.3 Declaration
It is used to declare methods and variables used in java code within a jsp file. In
jsp it is the rule to declare any variable before it is used.
Syntax: <%! Declaration;[declaration;]+…%>
Example: <%! int a=62; %>
3.6.4 JSP scriptlet Tag: please refer to( 3.5. a ) Scriptlet Tag
3.6.5 Expressions
Its contains the scripting language expressions which is gets evaluated and
converted to String by the JSP engine and it is meant to the output stream of the
response. So there is no need to write the out.print() method.
Example:
<html>
<body>
<%= “ a JSB String” %>
</body>
</html>
47
ADVANCE JAVA
Object Type
Out Javax.servlet.jsp.JspWriter
Request Javax.servlet.http.HttpservletRequest
Response Javax.servlet.http.HttpservletResponse
Config Javax.servlet.ServletConfig
Application Javax.servlet.ServletContext
Session Javax.servlet.http.HttpSession
pageContext Javax.servlet.jsp.PageContext
Page Java.lang.Objects
Exception Java.lang.Throwable
3.7.1out:- The out implicit object is an instance of a javax.servlet.jsp.JspWriter
object. It is used to send the content in a response.
48
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
Example: response.sendRedirect(http://www.google.com);
49
ADVANCE JAVA
3.7 Summary
This course will helps to build skills gained by the students in Java fundamentals
and advanced java programming skills.
3.9 Bilbliograpgy
https://www.javapoint.com
https://www.w3schools.in
50
Chapter 3: Introduction to Jsp Standard Tag Library (JSTl) And JSTL Tags
❖❖❖❖❖
51
ADVANCE JAVA
Module2
4
INTRODUCTION TO BEAN, STANDARD
ACTIONS, SESSION TRACKING TYPES AND
METHODS. CUSTOM TAGS
Unit Structure
4.0 Objectives
4.1 Introduction
4.2 Introduction to Bean
4.3 Standard actions
4.3.1 jsp:useBean
4.3.2 jsp:include
4.3.3 jsp:setProperty
4.3.4 jsp:forward
4.3.5 jsp:plugin
4.3.6 jsp:attribute
4.3.7 jsp:body
4.3.8 jsp:text
4.3.9 jsp:param
4.3.10jsp:attribute
4.3.11 jsp:output
4.4 session tracking types and methods
4.4.1 Cookies
4.4.2 Hidden Fields
4.4.3 URL Rewriting
4.4.4 Session Object
4.5 Custom tags
4.7 Reference for further reading
4.0 Objectives
EJP stands for Enterprise Java Beans. It is a server-side component. It means that
EJB is basically used at server-side coding. So if we have client-side and server-
side, EJB is used for server-side and not for client-side.
52
Chapter 4: Introduction To Bean, Standard Actions, Session Tracking Types and Methods. Custom Tags
4.1 Introduction
JavaBeans are nothing it’s a class that encapsulates many objects into a single
object that is nothing but a bean. Java beans should follow some protocol such as:
package mypack;
public class students implements java.io.Serializable
{
private int RollNo;
private String name;
public students(){}
public void setRollNo(int id)
{
this.RollNo=RollNo;
}
public int getId()
{
return RollNo;
}
public void setName(String name)
{
this.name=name;
53
ADVANCE JAVA
}
public String getName()
{
return name;
}
}
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test
{
public static void main(String args[])
{
students s=new students(); //object is created
s.setName("Rahul"); //setting value to the object
System.out.println(s.getName());
}
}
Standard actions in JSP are used to control the behaviour of the Servlets engine.
In JSP there are 11 standard actions tag. With the help of these tags we can
dynamically insert a file, reuse the beans components, forward user etc.
Syntax: <jsp:action_name attribute=”value” />
3 jsp:useBean
4 jsp:include
5 jsp:setProperty
6 jsp:forward
7 jsp:plugin
8 jsp:attribute
9 jsp:body
10 jsp:text
11 jsp:param
12 jsp:attribute
13 jsp:output
54
Chapter 4: Introduction To Bean, Standard Actions, Session Tracking Types and Methods. Custom Tags
4.3.1 jsp:useBean:- This action tag is used when we want to use beans in the
JSP page. Using this tag the beans can be easily invoked
Syntax: <jsp:useBean id=”” class=”” />
4.3.2 jsp:include:- This tag is used to insert a jsp file into another file , same as
include directive . It is compute at the time request processing phase.
Syntax: <jsp:include page=”page URL” flush=”true/false”>
4.3.3 jsp:setProperty:- This tag used to set the property of a bean. Before setting
this property we need define a bean.
Syntax: <jsp:setProperty name=”” property=””>
4.3.4 jsp:getProperty:- To get the property of a bean we use this tag. It inserts
the output in a string format which is converted into string.
Syntax: <jsp:getAttribute name=”” property=””>
4.3.5 jsp:forward:- It is basically used to forward the request to another jsp or
any static page. Here the request can be forwarded with or with no
parameters.
Syntax: <jsp:forward page=”value”>
4.3.6 jsp:plugin:- It is used for introducing Java components into JSP which is
detects the browser and adds the <object> or <embed> JSP tags into the file
Syntax: <jsp:plugin type=”applet/bean” code=”objectcode”
codebase=”objectcodebase”>
4.3.7 jsp:param:- It is the child object of the plugin object. It contains one or
more actions to provide additional parameters.
Syntax: <jsp:params>
<jsp:param nname=”val” value=”val”>
</jsp:param>
4.3.8 jsp:body:- This tag is used for defining the xml dynamically that is the
elements can be generated during the request time than at the compilation
time.
Syntax: <jsp:body></jsp:body>
4.3.9 jsp:attribute:-This tag is used for defining the xml dynamically that is the
elements can be generated during the request time than at the compilation
time.
Syntax: <jsp:attribute></jsp:attribute>
4.3.10 jsp:text:- To template text in JSP pages this tag is used. The body of this
tag does not contains any elements .It only contains text and EL
expressions.
Syntax: <jsp:text>template</jsp:text>
4.3.11jsp: output: - Its consists of XML template text which is placed within text
action objects.In this output is declared as XML and DOCTYPE.
Syntax: <jsp:output doctype-root-element=”” doctype –system=””>
55
ADVANCE JAVA
There are four techniques which can be used to identify a user session.
a) Cookies
b) Hidden Fields
c) URL Rewriting
d) Session Object
4.4.1 Cookie: -
A cookie is small information which is sent by the web server to a web
client. It is save at the client side for the given domain and path. It is
basically used to identify a client when sending a subsequent request. There
are two types of cookies:
a) Session cookies: these are temporary cookies and its get deleted as
soon as the user closes the browser and next time whenever the client
visits the same websites, server will treat the request as a new client
as cookies are already deleted.
b) Persistent Cookie: its remains on hard drive, until we delete them or
they gets expire.
4.4.2 Hidden Filed:
Hidden field are similar to other input fields with the only difference is that
these fields are not get displayed on the page but the values of these fields
are sent to other input fields.
For example: <input type=”hidden” name=”sessionId” value=”unique
value”/>
4.4.3 URL Rewriting:
It is a process of appending or modifying the url structure when loading a
page. The request made by the client is always treated as new request and
the server cannot identify whether the request is new one or the previous
same client .so due to this property of HTTP protocol and web servers are
called stateless.
4.4.4 Session Object:
It is used for session management. When a user enters a website for the first
time Httpsession is obtained via request. When session is created, server
generates aunique ID and attaches that ID with every request of that user to
server with which the server identifies the client.
How to access or get a session object: By calling getSession() method and it is
an implicit object.
a) HttpSession x=request.getSession()
b) HttpSession y=new request.getSession(Boolean)
56
Chapter 4: Introduction To Bean, Standard Actions, Session Tracking Types and Methods. Custom Tags
• Custom tags, also known as JSP tag extensions (because they extend the set
of built-in JSP tags), provide a way of encapsulating reusable functionality
on JSP pages.
• One of the major drawbacks of scripting environments such as JSP is that
it’s easy to quickly put together an application without thinking about how
it will be maintained and grown in the future.
• Use JavaBeans for representing and storing information and state. An
example is building JavaBeans to represent the business objects in your
application.
• Use custom tags to represent and implement actions that occur on those
JavaBeans, as well as logic related to the presentation of information.
• A example from JSTL is iterating over a collection of objects or conditional
logic.
• Custom tags have access to implicit objects like request, response, session,
etc
• JavaBeans are java classes but all java class are not java beans.
• major one is Custom tag which can be use by the java beans to
communicate with each other.
• JavaBeans are normal java classes and don't know anything about JSP.
• JavaBeans are normally used to maintain the data and custom tags for
functionality or implementing logic on jsp page.
4.6 Reference for further reading.
https://docs.oracle.com/javase/7/docs/api/
4.7 Bilbliograpgy
https://www.wideskills.com/jsp/jsp-session-tracking-techniques
https://www.geeksforgeeks.org/url-rewriting-using-java-servlet/
https://www.javatpoint.com/java-bean
https://www.javatpoint.com/what-is-ejb
https://www.w3schools.in
https://www.java-samples.com/showtutorial.php?tutorialid=607
57
ADVANCE JAVA
❖❖❖❖❖
58
Chapter 5: Introduction to Spring
Module 2
5
INTRODUCTION TO SPRING
Unit Structure
5.1 Objectives
5.2 Introduction to Spring Framework
5.3 POJO Programming Model
5.4 Lightweight Containers
5.4.1 Spring IOC Container
5.4.2 Configuration Metadata
5.4.3 Configuring and Using the Container
5.5 Summary
5.6 References
5.7 Unit End Exercises
5.1 Objectives:
This chapter would make you understand the following concepts:
• Spring Framework
• POJO programming model
• IoC container
• How to configure metadata with container
59
ADVANCE JAVA
60
Chapter 5: Introduction to Spring
Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language
modules the details of which are as follows −
• The Core module provides the fundamental parts of the framework,
including the IoC and Dependency Injection features.
• The Bean module provides BeanFactory, which is a sophisticated
implementation of the factory pattern.
• The Context module builds on the solid base provided by the Core and Beans
modules and it is a medium to access any objects defined and configured.
The ApplicationContext interface is the focal point of the Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and
Transaction modules whose detail is as follows −
• The JDBC module provides a JDBC-abstraction layer that removes the need
for tedious JDBC related coding.
• The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and
XStream.
• The Java Messaging Service JMS module contains features for producing
and consuming messages.
• The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your
POJOs.
Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet
modules the details of which are as follows −
• The Web module provides basic web-oriented integration features such as
multipart file-upload functionality and the initialization of the IoC container
using servlet listeners and a web-oriented application context.
• The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
61
ADVANCE JAVA
62
Chapter 5: Introduction to Spring
Employee.java:
// POJO class Exmaple
package Jtp.PojoDemo;
public class Employee
{ private String name;
private String id;
private double sal;
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public String getId() {
return id; }
public void setId(String id) {
this.id = id; }
public double getSal() {
return sal; }
public void setSal(double sal) {
this.sal = sal; }
}
To access the objects from the POJO class, follow the below steps:
✓ Create a POJO class objects
✓ Set the values using the set() method
✓ Get the values using the get() method
For example, create a MainClass.java class file within the same package and write
the following code in it:
MainClass.java:
//Using POJO class objects in MainClass Java program
package Jtp.PojoDemo;
public class MainClass {
public static void main(String[] args) {
// Create an Employee class object
Employee obj= new Employee(); //POJO class object created.
obj.setName("Alisha"); // Setting the values using the set() method
63
ADVANCE JAVA
obj.setId("A001");
obj.setSal(200000);
//Getting the values using the get() method
System.out.println("Name: "+ obj.getName());
System.out.println("Id: " + obj.getId());
System.out.println("Salary: " +obj.getSal());
}
}
Output:
Name: Alisha
Id: A001Salary: 200000.0
64
Chapter 5: Introduction to Spring
65
ADVANCE JAVA
this.message = message;
package com.example;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
obj.getMessage();
66
Chapter 5: Introduction to Spring
Please note:
• Use getBean() which uses bean ID to return a generic object to get the
required bean.
Following is the XML code for Beans.xml.
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
</beans>
After you run the application you will see the following message as output.
Your Message: Hello World!
67
ADVANCE JAVA
this.message = message;
68
Chapter 5: Introduction to Spring
package com.example;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.FileSystemXmlApplicationContext;
("C:/Users/ADMIN/workspace/HelloSpring/src/Beans.xml");
obj.getMessage();
Please note:
• Use getBean() which uses bean ID to return a generic object to get the
required bean.
69
ADVANCE JAVA
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</bean>
</beans>
• The configuration metadata allows you to express the objects that compose
your application and the rich interdependencies between such objects.
• Configuration metadata is supplied in a simple and intuitive XML format.
• Spring configuration consists of at least one and typically more than one
object definition that the container must manage. XML- based configuration
shows these objects as <object/> elements inside a top-level <objects/>
element.
• These object definitions correspond to the actual objects that make up your
application. Typically you define service layer objects, data access objects
(DAOs), presentation objects such as ASP.NET page instances,
infrastructure objects such as NHibernate SessionFactories, and so forth.
• The following example shows the basic structure of XML-based
configuration metadata:
70
Chapter 5: Introduction to Spring
<objects xmlns="http://www.springframework.net">
<object id="..." type="...">
<!-- collaborators and configuration for this object go here -->
</object>
<object id="...." type="...">
<!-- collaborators and configuration for this object go here -->
</object>
<!-- additional collaborators and configuration for this object go here -->
</object>
<!-- more object definitions for services go here -->
</objects>
(Note : the service layer consists of the class PetStoreService.)
71
ADVANCE JAVA
The IApplicationContext enables you to read object definitions and access them as
follows:
// create and configure objects
IApplicationContext context = new XmlApplicationContext("services.xml",
"daos.xml");
// retrieve configured instance
PetStoreService service = (PetStoreService)
context.GetObject("PetStoreService");
// use configured instance
IList userList = service.GetUserNames();
5.5 Summary:
5.6 References :
Reference Books:
➢ Java 6 Programming Black Book, Wiley–Dreamtech ISBN 10:
817722736X ISBN 13: 9788177227369
➢ Spring in Action, Craig Walls, 3rd Edition,Manning, ISBN 9781935182351
➢ Professional Java Development with the Spring Framework by Rod
Johnsonet al.John Wiley & Sons 2005 (672 pages) ISBN:0764574833
72
Chapter 5: Introduction to Spring
❖❖❖❖❖
73
ADVANCE JAVA
Module 2
6
SPRING FRAMEWORKS
Unit Structure
6.1 Objectives
6.2 Dependency Injection
6.2.1 Setter Injection
6.2.2 Constructor Injection
6.3 Circular Dependency
6.4 Overriding Bean
6.5 Auto Wiring
6.6 Bean Looksup
6.7 Spring manages Beans
6.8 Summary
6.9 References
6.10 Unit End Exercises
6.1 Objectives
• ȋ Ȍ
ǡ ǡ ǡ
Ǥ
• Ǥ
• ǡ Ǧ
Ǧ Ǥ
74
Chapter 6: Spring Frameworks
75
ADVANCE JAVA
There are the issue caused during dependency injection when spring-context tries
to load objects and one bean depends on another bean. Suppose when Object A &
B depends on each other.
i.e. A depends on B and vice-versa.
Spring throws UnsatisfiedDependencyException while creating objects of A and B
because A object cannot be created until unless B is created and visa-versa.
76
Chapter 6: Spring Frameworks
To simulate the circular dependency issue, run the below class, and see the
console log.
CircularDependenciesTestApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CircularDependenciesTestApp {
public static void main(String[] args) {
SpringApplication.run(CircularDependenciesTestApp.class, args);
}
}
When we execute CircularDependenciesTestApp class it won’t be able to inject
the dependencies due to circular dependencies on each other and will throw a
checked exception as shown below:
console log
Error starting ApplicationContext. To display the conditions report re-run your
application with 'debug' enabled.
2020-05-27 21:22:46.368 ERROR 4480 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| serviceA defined in file [F:\sts4-workspace\circular-dependencies-
spring\target\classes\org\websparrow\service\ServiceA.class]
↑ ↓
| serviceB defined in file [F:\sts4-workspace\circular-dependencies-
spring\target\classes\org\websparrow\service\ServiceB.class]
└─────┘
6.3.1 How to resolve this issue?
To solve the circular dependency issue, you have two options: Using @Lazy with
constructor injection and Using @Autowired along with @Lazy annotation.
77
ADVANCE JAVA
78
Chapter 6: Spring Frameworks
79
ADVANCE JAVA
80
Chapter 6: Spring Frameworks
81
ADVANCE JAVA
}
}
Here is the content of HelloIndia.java file −
public class HelloIndia
{
private String message1;
private String message2;
private String message3;
public void setMessage1(String message){
this.message1 = message;
}
public void setMessage2(String message){
this.message2 = message;
}
public void setMessage3(String message){
this.message3 = message;
}
public void getMessage1(){
System.out.println("India Message1 : " + message1);
}
public void getMessage2(){
System.out.println("India Message2 : " + message2);
}
public void getMessage3(){
System.out.println("India Message3 : " + message3);
}
}
Following is the content of the MainApp.java file −
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp
{
public static void main(String[] args)
{
ApplicationContext context = new
ClassPathXmlApplicationContext("Beans.xml");
82
Chapter 6: Spring Frameworks
objB.getMessage2();
objB.getMessage3();
}
}
Once you are done creating the source and bean configuration files, let us run the
application. If everything is fine with your application, it will print the following
message −
World Message1 : Hello World!
World Message2 : Hello Second World!
India Message1 : Hello India!
India Message2 : Hello Second World!
India Message3 : Namaste India!
(Note:If you observed here, we did not pass message2 while creating "helloIndia"
bean, but it got passed because of Bean Definition Inheritance.)
83
ADVANCE JAVA
Note : You can use byType or constructor autowiring mode to wire arrays and
other typed-collections.
Limitations with autowiring:
Autowiring works best when it is used consistently across a project. If autowiring
is not used in general, it might be confusing for developers to use it to wire only
one or two bean definitions. Though, autowiring can significantly reduce the need
to specify properties or constructor arguments but you should consider the
limitations and disadvantages of autowiring before using them.
Sr.No. Limitations Description
1 Overriding possibility You can still specify dependencies using
<constructor-arg> and <property>
settings which will always override
autowiring.
84
Chapter 6: Spring Frameworks
85
ADVANCE JAVA
Step 3:
@Test
public void whenLookupMethodCalled_thenNewInstanceReturned() {
// ... initialize context
StudentServices first = this.context.getBean(StudentServices.class);
StudentServices second = this.context.getBean(StudentServices.class);
assertEquals(first, second);
assertNotEquals(first.getNotification(), second.getNotification());
}
(Note that in StudentServices, we left the getNotification method as a stub)
ǤǤʹ
Let's enhance StudentNotification with some state:
Step 1:
@Component
@Scope("prototype")
public class SchoolNotification {
@Autowired Grader grader;
private String name;
private Collection<Integer> marks;
public SchoolNotification(String name) {
// ... set fields
}
// ... getters and setters
public String addMark(Integer mark) {
this.marks.add(mark);
return this.grader.grade(this.marks);
}
}
Now, it is dependent on some Spring context and also additional context that we
will provide procedurally.
86
Chapter 6: Spring Frameworks
Step 2:We can then add a method to StudentServices that takes student data
and persists it.
public abstract class StudentServices {
private Map<String, SchoolNotification> notes = new HashMap<>();
@Lookup
protected abstract SchoolNotification getNotification(String name);
public String appendMark(String name, Integer mark) {
SchoolNotification notification
= notes.computeIfAbsent(name, exists -> getNotification(name)));
return notification.addMark(mark);
}
}
At runtime, Spring will implement the method in the same way, with a couple of
additional tricks.
Please note:
✓ 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.It does this by implementing getSchoolNotification with a call to
beanFactory.getBean(SchoolNotification.class, name).
✓ Second, we can sometimes make the @Lookup-annotated method abstract,
like the above example.
@Test
public void whenAbstractGetterMethodInjects_thenNewInstanceReturned() {
// ... initialize context
StudentServices services = context.getBean(StudentServices.class);
assertEquals("PASS", services.appendMark("Alex", 89));
assertEquals("FAIL", services.appendMark("Bethany", 78));
assertEquals("PASS", services.appendMark("Claire", 96));
}
With this setup, we can add Spring dependencies as well as method dependencies
to SchoolNotification.
87
ADVANCE JAVA
88
Chapter 6: Spring Frameworks
While executing this application, we'll use applicationContext object and call
its getBeanDefinitionNames() method, which will return all the beans in our
applicationContext container:
@SpringBootApplication
public class Application
{ private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
displayAllBeans();
}
public static void displayAllBeans() {
String[] allBeanNames = applicationContext.getBeanDefinitionNames();
for(String beanName : allBeanNames) {
System.out.println(beanName);
}
}
}
This will print all the beans from applicationContext container:
fooController
fooService
//other beans
6.7.2 Using Spring Boot Actuator
The Spring Boot Actuator functionality provides endpoints which are used for
monitoring our application's statistics.
It includes many built-in endpoints, including /beans. This displays a complete list
of all the Spring managed beans in our application. You can find the full list of
existing endpoints over on the official docs.
Now, we'll just hit the URL http://<address>:<management-port>/beans. We
can use our default server port if we haven't specified any separate
management port. This will return a JSON response displaying all the beans
within the Spring IoC Container:
You will get output like this:
[ { "context": "application:8080", "parent": null, "beans": [ { "bean":
"fooController", "aliases": [], "scope": "singleton", "type":
"com.baeldung.displayallbeans.controller.FooController", "resource": "file
[E:/Workspace/tutorials-master/spring-boot/target
/classes/com/baeldung/displayallbeans/controller/FooController.class]",
89
ADVANCE JAVA
6.8 Summary:
6.9 References :
Reference Books:
➢ Java 6 Programming Black Book, Wiley–Dreamtech ISBN 10:
817722736X ISBN 13: 9788177227369
➢ Spring in Action, Craig Walls, 3rd Edition,Manning, ISBN 9781935182351
➢ Professional Java Development with the Spring Framework by Rod
Johnsonet al.John Wiley & Sons 2005 (672 pages) ISBN:0764574833
➢ Beginning Spring , Mert Calıs kan and KenanSevindik Published by John
Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256
Web References:
➢ https://www.springframework.net/
➢ https://www.javadevjournal.com/
➢ https://www.tutorialspoint.com/
➢ https://www.geeksforgeeks.org/
90
Chapter 6: Spring Frameworks
91
ADVANCE JAVA
Module 2
7
SPRING AND AOP
Unit Structure
7.0 Objectives
7.1 Introduction
7.2 An Overview
7.2.1 What is spring AOP and about AspectJ?
7.2.2 Concept and Terminology used in AOP with examples
7.2.3 Advantages and disadvantages of spring AOP
7.2.4 Types of advices
7.2.5 Definition of Point Cut, Designator, Annotations
7.3 Summary
7.4 Exercise
7.5 List of References
7.0 Objectives
After going through this unit, you will be able to:
• what is spring AOP?
• how AOP different from OOPS
• terminology and concepts of AOP with example and advantages and
disadvantages of spring AOP, types of advices.
• Introduction of AspectJ, spring boot AOP
7.1 Introduction
Aspect Oriented Programming (AOP) complements Object-Oriented Programming
(OOP) by providing another way of thinking about program structure. The key unit
of modularity in OOPis the class, whereas in AOP the unit of modularity is the
aspect. Aspect Oriented Pro-gramming AspectJ integrated with Spring AOP
provides very powerful mechanisms for stronger enforcement of security.Aspect-
oriented programming (AOP) allows weaving a security aspect into an application
providing additional security functionality or introducing completely new security
mechanisms.Implementation of security with AOP is a flexible method to develop
sepa-rated, extensible and reusable pieces of code called aspects.In this
comparative study paper, we argue that Spring AOP pro-vides stronger
enforcement of security than AspectJ
92
Chapter 7: Spring and Aop
7.2 An Overview
7.2. 1. What is Spring AOP (Aspect Oriented Programming) and about AspectJ?
Aspect-oriented programming (AOP) is one of the major components of the Spring
Framework. The Spring AOP helps in breaking down the logic of the program into
several distinct parts called as concerns. Cross-cutting concerns is the functions
which span multiple points of an application.
The cross-cutting concerns help in increasing the modularity and separate it from
the business logic of an application. Also, a cross-cutting is a concern that affects
the whole application and it should be centralized in one location in code as
possible such as authentication, transaction management, logging etc.
Below diagram shows how the concerns like logging, security, and transaction
management are cutting across different layer here:
93
ADVANCE JAVA
• Caching
• Internationalization
• Error detection and correction
• Memory management
• Performance monitoring
• Synchronization
We can implement Spring Framework AOP in pure Java, it doesn’t require to the
special compilation process. It is the best choice for use in a J2EE web container
or application server because it doesn’t require to control the class loader hierarchy.
class A{
public void m1(){...}
public void m2(){...}
public void m3(){...}
public void m4(){...}
public void m5(){...}
public void n1(){...}
public void n2(){...}
public void p1(){...}
public void p2(){...}
public void p3(){...}
}
These are the 5 methods that start from m while 2 methods start from n and 3
methods starting from p.
• The Scenario: You have to maintain the log and send the notification after
calling methods starting from m.
• A problem without using the AOP: You can call methods which maintain
logs and sends the notification from the methods starting with m. For that,
you need to write code for all the 5 methods.
• The solution with Aspect Oriented Programming: You don’t have to call
methods from the method. You can define additional concerns like
maintaining a log, sending notification etc. as a method of a class.
94
Chapter 7: Spring and Aop
Some of the cases where AOP is frequently used: To provide declarative enterprise
services. For example, as declarative transaction management. It allows users for
implementing custom aspects
* About AspectJ
The important aspect of Spring is the Aspect-Oriented Programming
(AOP) framework. As we all know, the key unit of modularity in OOP(Object
Oriented Programming) is the class, similarly, in AOP the unit of modularity is the
aspect. Aspects enable the modularization of concerns such as transaction
management that cut across multiple types and objects. To implement these
concerns, AspectJ comes into the picture. AspectJ, a compatible extension to the
Java programming language, is one implementation of AOP. It has grown into a
complete and popular AOP framework. Since AspectJ annotations are supported
by more and more AOP frameworks, AspectJ-style aspects are more likely to be
reused in other AOP frameworks that support AspectJ.
95
ADVANCE JAVA
Note : “Spring Boot is a project that is built on the top of the Spring
Framework. It provides an easier and faster way to set up, configure, and run
both simple and web-based applications”.
There are many ways to create a Spring Boot application. These are following:
96
Chapter 7: Spring and Aop
97
ADVANCE JAVA
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Employee.java
Create a simple Employee POJO class (You can use it as JPA entity for database
operations):
98
Chapter 7: Spring and Aop
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" +
lastName + ", emailId=" + emailId +
"]";
}
}
EmployeeService.java
99
ADVANCE JAVA
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
/**
* Employee Service
*
*
*/
@Service
public class EmployeeService {
private List < Employee > employees = new ArrayList < > ();
public List < Employee > getAllEmployees() {
System.out.println("Method getAllEmployees() called");
return employees;
}
public Employee getEmployeeById(Long employeeId) {
System.out.println("Method getEmployeeById() called");
for (Employee employee: employees) {
if (employee.getId() == Long.valueOf(employeeId)) {
return employee;
}
}
return null;
}
public void addEmployee(Employee employee) {
System.out.println("Method addEmployee() called");
employees.add(employee);
}
public void updateEmployee(Employee employeeDetails) {
System.out.println("Method updateEmployee() called");
for (Employee employee: employees) {
if (employee.getId() == Long.valueOf(employeeDetails.getId())) {
employees.remove(employee);
employees.add(employeeDetails);
}
100
Chapter 7: Spring and Aop
}
}
public void deleteEmployee(Long employeeId) {
System.out.println("Method deleteEmployee() called");
for (Employee employee: employees) {
if (employee.getId() == Long.valueOf(employeeId)) {
employees.remove(employee);
}
}
}
}
LoggingAspect.java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Aspect for logging execution.
*
*
*/
@Aspect
@Component
public class LoggingAspect {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Before("execution(*springboot2.springaop.service.EmployeeService.*(..))")
public void logBeforeAllMethods(JoinPoint joinPoint) {
LOGGER.debug("****LoggingAspect.logBeforeAllMethods() : " +
joinPoint.getSignature().getName());
}
101
ADVANCE JAVA
@Before("execution(*springboot2.springaop.service.EmployeeService.getEmplo
yeeById(..))")
public void logBeforeGetEmployee(JoinPoint joinPoint) {
LOGGER.debug("****LoggingAspect.logBeforeGetEmployee() : " +
joinPoint.getSignature().getName());
}
@Before("execution(*springboot2.springaop.service.EmployeeService.createEm
ployee(..))")
public void logBeforeAddEmployee(JoinPoint joinPoint) {
LOGGER.debug("****LoggingAspect.logBeforeCreateEmployee() : " +
joinPoint.getSignature().getName());
}
@After("execution(* springboot2.springaop.service.EmployeeService.*(..))")
public void logAfterAllMethods(JoinPoint joinPoint)
{
LOGGER.debug("****LoggingAspect.logAfterAllMethods() : " +
joinPoint.getSignature().getName());
}
@After("execution(*
springboot2.springaop.service.EmployeeService.getEmployeeById(..))")
public void logAfterGetEmployee(JoinPoint joinPoint)
{
LOGGER.debug("****LoggingAspect.logAfterGetEmployee() : " +
joinPoint.getSignature().getName());
}
@After("execution(*springboot2.springaop.service.EmployeeService.addEmploy
ee(..))")
public void logAfterAddEmployee(JoinPoint joinPoint)
{
LOGGER.debug("****LoggingAspect.logAfterCreateEmployee() : " +
joinPoint.getSignature().getName());
}
}
102
Chapter 7: Spring and Aop
Application.java
Now test the AOP configuration and other stuff with main() method:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import springboot2.springaop.model.Employee;
import springboot2.springaop.service.EmployeeService;
@SpringBootApplication
public class Application {
Output
103
ADVANCE JAVA
@Aspect
@Component
public class LoggingAspect {
...
}
Join point
Join point is a point during the execution of a program, such as the execution of a
method or the handling of an exception. In Spring AOP, a join point always
represents a method execution.
In our example, all the methods defined inside EmployeeService are joint points.
Advice
Advice is an action taken by an aspect at a particular join point.
In our
example, logBeforeAllMethods(), logBeforeGetEmployee(), logBeforeAddEmploy
ee(), logAfterAllMethods(), logAfterGetEmployee(),
and logAfterAddEmployee() methods are advices.
Pointcut
A Pointcut is a predicate that helps match an Advice to be applied by an Aspect at
a particular JoinPoint. The Advice is often associated with a Pointcut expression
and runs at any Joinpoint matched by the Pointcut.
In our example, the expressions passed in @Before and @After annotations are
pointcuts. For example:
@Before("execution(*springboot2.springaop.service.EmployeeService.*(..))")
@After("execution(* springboot2.springaop.service.EmployeeService.*(..))")
104
Chapter 7: Spring and Aop
Target object
An object being advised by one or more aspects. Also referred to as the “advised
object”. Since Spring AOP is implemented by using runtime proxies, this object
is always a proxied object.
AOP proxy
An object created by the AOP framework in order to implement the aspect contracts
(advise method executions and so on). In the Spring Framework, an AOP proxy is
a JDK dynamic proxy or a CGLIB proxy.
In our example, a proxy object is created when we ask the bean reference
for EmployeeService class.
105
ADVANCE JAVA
• Before advice: Advice that executes before a join point, but which does not
have the ability to prevent execution flow proceeding to the join point (unless
it throws an exception).
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doAccessCheck() {
// ...
}
}
106
Chapter 7: Spring and Aop
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
@AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
// ...
}
}
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
public class AfterThrowingExample {
@AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doRecoveryActions() {
// ...
}
}
107
ADVANCE JAVA
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
public class AfterFinallyExample {
@After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doReleaseLock() {
// ...
}
}
Example:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@Aspect
public class AroundExample {
@Around("com.xyz.myapp.SystemArchitecture.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
return retVal;
}
}
108
Chapter 7: Spring and Aop
7.3 Summary
In this Spring AOP chapter, you learned about the Aspect-oriented programming
in Spring Framework. You also saw the need for using Spring AOP, where to use
it. Along with that, you saw its terminologies ,advantages and disadvantages of
spring AOP the types of advice with help of examples, introduction of AspectJ,
spring boot . Still, you had a doubt go through references and bibliography
7.4 Exercise :-
109
ADVANCE JAVA
7.5 References:-
❖❖❖❖❖
110
Chapter 8: JDBC Data Access with Spring
Module 2
8
JDBC DATA ACCESS WITH SPRING
Unit Structure
8.0 Objectives
8.1 Introduction
8.1.1 Type 1 driver- JDBC-ODBC Bridge
8.1.2 Type 2 driver – Native-API driver
8.1.3 Type 3 driver – Network-Protocol driver (middleware driver)
8.1.4 Type 4 driver – Database-Protocol driver/Thin Driver
(Pure Java driver)
8.1.5 Type 5: highly-functional drivers with superior performance
8.2 Managing JDBC Connection
8.3 Configuring Data Source to obtain JDBC Connection
8.4 Data Access operations with JDBC Template and Spring
8.5 RDBMS Operation classes
8.6 Modeling JDBC operations as Java objects
8.6.1 Java Database Connectivity with MySQL
8.7 Conclusion
8.8 List of references
8.0 OBJECTIVES
JDBC stands for Java Database Connectivity. Driver play role like to move an
object from one place to another. Vehicle drivers are playing role to move vehicle
as well objects whose included inside the vehicles from one place to another. JDBC
APIs are used to access virtually any kind of data source from anywhere. JDBC is
one type of API which connect and execute the query with the database. JDBC is
part of JAVA SE (Java Standard Edition). JDBC API uses JDBC drivers to connect
with different types of databases.
111
ADVANCE JAVA
8.1 INTRODUCTION
JDBC Drivers are used to manipulate data from database with the help of java
platform. JDBC perform all types of SQL operations with java. JDBC have its five
different types of drivers as follows:
a. JDBC-ODBC Bridge
b. Native Driver
c. Network Protocol Driver
d. Thin Driver
e. Highly-Functional Driver
10.1.1 Type 1 driver- JDBC-ODBC Bridge:
112
Chapter 8: JDBC Data Access with Spring
113
ADVANCE JAVA
• The JDBC type 2 driver, also known as the Native-API driver, is a database
driver implementation that uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API. For
example: Oracle OCI driver is a type 2 driver.
• The JDBC type 3 driver, also known as the Pure Java driver for database
middleware, is a database driver implementation which makes use of
a middle tier between the calling program and the database. The middle-tier
114
Chapter 8: JDBC Data Access with Spring
• This differs from the type 4 driver in that the protocol conversion logic
resides not at the client, but in the middle-tier. Like type 4 drivers, the type 3
driver is written entirely in Java.
• The same client-side JDBC driver may be used for multiple databases. It
depends on the number of databases the middleware has been configured to
support. The type 3 driver is platform-independent as the platform-related
differences are taken care of by the middleware. Also, making use of the
middleware provides additional advantages of security and firewall access.
115
ADVANCE JAVA
• The JDBC type 4 driver, also known as the Direct to Database Pure Java
Driver, is a database driver implementation that converts JDBC calls directly
into a vendor-specific database protocol.
• As the database protocol is vendor specific, the JDBC client requires separate
drivers, usually vendor supplied, to connect to different types of databases.
116
Chapter 8: JDBC Data Access with Spring
• Any JDBC drivers that are fundamentally based on the Type 4 architecture
yet are designed to address all or most of these limitations represent a drastic
departure from the norm. In fact, such drivers could be classified as an
117
ADVANCE JAVA
entirely new type. Call them what you will, but for the purposes of this
discussion, they are “Type 5.”
• Not all developers truly understand the role JDBC middleware plays in
application-to-data operations, beyond simply enabling connectivity. In fact,
with the increased abstraction of object modeling and higher-level
applications, many a developer views JDBC drivers as vital but “dumb” pipes
rather than critical cogs that not only drive the success of an application stack
but also enhance it.
• For this reason, some in the developer community may take a “so-what?”
attitude toward the notion of a JDBC Type 5 driver. They may even reject the
whole notion of a data connectivity driver as a component where innovations
such as application failover for high availability ought to take place. Such
innovations, they could reason, are more appropriately handled at the higher
application level. This reasoning, however, is very debatable.
➢ The Limits of previous driver (Type 4):
Among developers who are knowledgeable about the behind-the-scenes workings
of middleware data connectivity using JDBC drivers, the limitations of a Type 4
driver are generally undisputable. These include:
• The need to write and maintain code specific to each supported data source.
Even with modern framework-based object-relational mapping (ORM)
models, JDBC Type 4 drivers typically require the use of proprietary code to
support variant database features such as BLOBs and CLOBs, high
availability, and XA.
• Poor and/or inconsistent driver response times or data throughput
performance when the driver is deployed in certain runtime environments
(such as different JVMs) or with ORMs and application servers.
• The inability to tune or optimize critical applications, or the ability to do so
only with considerable application downtime.
• Poor virtual machine (VM) consolidation ratios due to inefficient runtime
CPU usage and high memory footprints.
• Deployment headaches such as having to deploy multiple JARs to support
different JVMs or database versions, or DLLs to support certain driver or
database functionality.
These limitations point to the following key trends and advances in the modern
Java environment as the sources of today’s Type 4 driver challenges:
118
Chapter 8: JDBC Data Access with Spring
119
ADVANCE JAVA
120
Chapter 8: JDBC Data Access with Spring
121
ADVANCE JAVA
To set up JDBC connectivity, you configure connection pools, Data Source objects
(always recommended, but optional in some cases), and MultiPools (optional) by
defining attributes in the Administration Console or, for dynamic connection pools,
in application code or at the command line.
➢ There are three types of transaction scenarios:
▪ Local transactions—non-distributed transactions
▪ Distributed transactions using an XA Driver—distributed transactions
with multiple participants that use two-phase commit
▪ Distributed transactions using a non-XA Driver—transactions with a
single resource manager and single database instance that emulate two-
phase commit
➢ You configure Data Source objects (DataSources and TxDataSources),
connection pools, and MultiPools according to the way transactions are
handled in your system. The following table summarizes how to configure
these objects for use in the three transaction scenarios:
Table Summary of JDBC Configuration Guidelines
122
Chapter 8: JDBC Data Access with Spring
123
ADVANCE JAVA
✓ Password: It is the password given by the user at the time of installing the
mysql database. In this example, we are going to use root as the password.
➢ Let's first create a table in the mysql database, but before creating table, we
need to create database first.
create database idol;
use idol;
create table student(id int(10),name varchar(40),age int(3));
Code:
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ idol ","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student ");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
➢ To connect java application with the mysql database, mysqlconnector.jar
file is required to be loaded.
124
Chapter 8: JDBC Data Access with Spring
125
ADVANCE JAVA
4) Create DAO interface StudentDAO and list down all the required methods.
Though it is not required and you can directly write StudentJDBCTemplate
class, but as a good practice, let’s do it.
5) Create other required Java classes Student, StudentMapper,
StudentJDBCTemplate and MainApp under the com.tutorialspoint package.
6) Make sure you already created Student table in TEST database. Also make
sure your MySQL server is working fine and you have read/write access on
the database using the give username and password.
7) Create Beans configuration file Beans.xml under the src folder.
8) The final step is to create the content of all the Java files and Bean
Configuration file and run the application as explained below.
Following is the content of the Data Access Object interface file
StudentDAO.java
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. Connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to create
* a record in the Student table.
*/
public void create(String name, Integer age);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
/**
* This is the method to be used to list down
126
Chapter 8: JDBC Data Access with Spring
127
ADVANCE JAVA
return id;
}
}
Following is the content of the StudentMapper.java file
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt(“id”));
student.setName(rs.getString(“name”));
student.setAge(rs.getInt(“age”));
return student;
}
}
Following is the implementation class file StudentJDBCTemplate.java for the
defined StufentDAO
interface StudentDAO.
Package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String SQL = “insert into Student (name, age) values (?, ?)”;
jdbcTemplateObject.update( SQL, name, age);
System.out.println(“Created Record Name = “ + name + “ Age = “ + age);
return;
}
128
Chapter 8: JDBC Data Access with Spring
129
ADVANCE JAVA
System.out.println(“------Records Creation--------" );
studentJDBCTemplate.create(“Virat”, 33);
studentJDBCTemplate.create(“Rohit”, 34);
studentJDBCTemplate.create(“Hardik”, 29);
System.out.println(“------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print(“ID : “ + record.getId() );
System.out.print(“, Name : “ + record.getName() );
System.out.println(“, Age : “ + record.getAge());
}
System.out.println(“----Updating Record with ID = 2 -----" );
studentJDBCTemplate.update(2, 20);
System.out.println(“----Listing Record with ID = 2 -----" );
Student student = studentJDBCTemplate.getStudent(2);
System.out.print(“ID : “ + student.getId() );
System.out.print(“, Name : “ + student.getName() );
System.out.println(“, Age : “ + student.getAge());
}
}
Following is the configuration file Beans.xml
<?xml version = “1.0” encoding = “UTF-8”?>
<beans xmlns = “http://www.springframework.org/schema/beans”
xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation = “http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd “>
<!–Initialization for data source →
<bean id=”dataSource”
class = “org.springframework.jdbc.datasource.DriverManagerDataSource”>
<property name = “driverClassName” value = “com.mysql.jdbc.Driver”/>
<property name = “url” value = “jdbc:mysql://localhost:3306/TEST”/>
<property name = “username” value = “root”/>
<property name = “password” value = “password”/>
</bean>
<!–Definition for studentJDBCTemplate bean →
<bean id = “studentJDBCTemplate”
class = “com.tutorialspoint.StudentJDBCTemplate”>
130
Chapter 8: JDBC Data Access with Spring
131
ADVANCE JAVA
132
Chapter 8: JDBC Data Access with Spring
133
ADVANCE JAVA
parameters then we would use one of the execute methods that takes an array
of parameter values passed in as varargs.
Public List<Actor> searchForActors(int age, String namePattern) {
List<Actor> actors = actorSearchMappingQuery.execute(age,
namePattern);
return actors;
}
8.6.3 SqlUpdate:
134
Chapter 8: JDBC Data Access with Spring
• The inherited sql property will be the name of the stored procedure in the
RDBMS.
• In addition to the name and the SQL type you can specify additional options.
For in parameters you can specify a scale for numeric data or a type name for
custom database types. For out parameters you can provide a RowMapper to
handle mapping of rows returned from a REF cursor. Another option is to
specify an SqlReturnType that provides and opportunity to define customized
handling of the return values.
135
ADVANCE JAVA
Import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class StoredProcedureDao {
private GetSysdateProcedure getSysdate;
@Autowired
public void init(DataSource dataSource) {
this.getSysdate = new GetSysdateProcedure(dataSource);
}
public Date getSysdate() {
return getSysdate.execute();
}
private class GetSysdateProcedure extends StoredProcedure {
private static final String SQL = “sysdate”;
public GetSysdateProcedure(DataSource dataSource) {
setDataSource(dataSource);
setFunction(true);
setSql(SQL);
declareParameter(new SqlOutParameter(“date”, Types.DATE));
compile();
}
public Date execute() {
// the ‘sysdate’ sproc has no input parameters, so an empty Map is
supplied…
Map<String, Object> results = execute(new HashMap<String,
Object>());
Date sysdate = (Date) results.get(“date”);
return sysdate;
}
}
136
Chapter 8: JDBC Data Access with Spring
}
Below is an example of a StoredProcedure that has two output parameters
(in this case Oracle REF cursors).
Import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
public class TitlesAndGenresStoredProcedure extends StoredProcedure {
private static final String SPROC_NAME = “AllTitlesAndGenres”;
public TitlesAndGenresStoredProcedure(DataSource dataSource) {
super(dataSource, SPROC_NAME);
declareParameter(new SqlOutParameter(“titles”,
OracleTypes.CURSOR, new TitleMapper()));
declareParameter(new SqlOutParameter(“genres”,
OracleTypes.CURSOR, new GenreMapper()));
compile();
}
public Map<String, Object> execute() {
// again, this sproc has no input parameters, so an empty Map is
supplied
return super.execute(new HashMap<String, Object>());
}
}
• Notice how the overloaded variants of the declareParameter(..) method that
have been used in the TitlesAndGenresStoredProcedure constructor are
passed RowMapper implementation instances; this is a very convenient and
powerful way to reuse existing functionality. (The code for the two
RowMapper implementations is provided below in the interest of
completeness.)
137
ADVANCE JAVA
import java.sql.SQLException;
import com.foo.domain.Title;
public final class TitleMapper implements RowMapper<Title> {
public Title mapRow(ResultSet rs, int rowNum) throws SQLException {
Title title = new Title();
title.setId(rs.getLong(“id”));
title.setName(rs.getString(“name”));
return title;
}
}
Second, the GenreMapper class, which again simply maps a ResultSet to a
Genre domain object for each row in the supplied ResultSet.
Import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Genre;
public final class GenreMapper implements RowMapper<Genre> {
public Genre mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Genre(rs.getString(“name”));
}
}
• If you need to pass parameters to a stored procedure (that is the stored
procedure has been declared as having one or more input parameters in its
definition in the RDBMS), you should code a strongly typed execute(..)
method which would delegate to the superclass’ (untyped) execute(Map
parameters) (which has protected access); for example:
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
import javax.sql.DataSource;
import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TitlesAfterDateStoredProcedure extends StoredProcedure {
private static final String SPROC_NAME = “TitlesAfterDate”;
private static final String CUTOFF_DATE_PARAM = “cutoffDate”;
138
Chapter 8: JDBC Data Access with Spring
8.5 Conclusion
This module explored the role of JDBC in providing solution developers with
enterprise-wide database connectivity capabilities and the JDBC architecture.
You studied the relationship between JDBC and Java. You learned about various
database systems and how JDBC was designed to work with relational DBMSs
and the relational command language, SQL. You learned about two and n-tier
application models. Finally, you learned about how JBDC was designed to
leverage the power of Java.
Specifically, you learned to:
1. Distinguish the role and place of JDBC among the Java technologies
2. Differentiate between DBMS types
3. Explain the relational model
4. Describe design considerations for JDBC and ODBC in a solution
5. Explain what SQL is and its role in database processing
6. Explain JDBC as it functions in two and n-tier system designs
7. Describe the capabilities of Java and a DBMS used with JDBC
https://www.javatpoint.com/steps-to-connect-to-the-database-in-java
https://en.wikipedia.org/wiki/Java_Database_Connectivity
❖❖❖❖❖
139
ADVANCE JAVA
Module 2
9
JDBC ARCHITECTURE
Unit Structure
9.0 Objectives
9.1 Introduction
9.2 JDBC Architecture
9.2.1 Two-tier Architecture
9.2.2 Three-tier Architecture
9.3 Basic JDBC Program using DML operation
9.4 conclusion
9.5 List of references
9.0 Objectives
The Java Database Connectivity is a standard Java API specifying interfaces for
connectivity between the Java applications and a wide range of databases. The
JDBC contains methods to connect to a database server, send queries to create a
table, update, delete, insert records in a database, retrieve and process the results
obtained from a database. Nowadays, there are a lot of frameworks that are built
for easier work with databases. But they contain the JDBC under the hood.
9.1 Introduction
JDBC or Java Database Connectivity is a specification from Sun microsystems
that provides a standard abstraction(that is API or Protocol) for java applications
to communicate with various databases. It provides the language with java
database connectivity standard. It is used to write programs required to access
databases. JDBC along with the database driver is capable of accessing databases
and spreadsheets. The enterprise data stored in a relational database(RDB) can be
accessed with the help of JDBC APIs.
140
Chapter 9: JDBC Architecture
• In the two-tier model, a Java applet or application talks directly to the data
source. This requires a JDBC driver that can communicate with the particular
data source being accessed. A user's commands are delivered to the database
or other data source, and the results of those statements are sent back to the
user. The data source may be located on another machine to which the user
is connected via a network. This is referred to as a client/server configuration,
with the user's machine as the client, and the machine housing the data source
as the server. The network can be an intranet, which, for example, connects
employees within a corporation, or it can be the Internet.
141
ADVANCE JAVA
them to the user. MIS directors find the three-tier model very attractive
because the middle tier makes it possible to maintain control over access and
the kinds of updates that can be made to corporate data. Another advantage
is that it simplifies the deployment of applications. Finally, in many cases,
the three-tier architecture can provide performance advantages.
9.2.2 Three-tier Architecture:
• All of these different executables are able to access a database with the use
of a JDBC driver as a middle tier: Java Desktop Applications, Java Applets,
Java Servlets, Java Server Pages (JSPs), Enterprise JavaBeans (EJBs).
142
Chapter 9: JDBC Architecture
• Until recently, the middle tier has often been written in languages such as C
or C++, which offer fast performance. However, with the introduction of
optimizing compilers that translate Java bytecode into efficient machine-
specific code and technologies such as Enterprise JavaBeans™, the Java
platform is fast becoming the standard platform for middle-tier development.
This is a big plus, making it possible to take advantage of Java's robustness,
multithreading, and security features.
143
ADVANCE JAVA
144
Chapter 9: JDBC Architecture
5. Database Server: It is nothing but the Database server like Oracle, MySQL,
SQL Server, etc. with which the JDBC client wants to communicate.
// getting connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"vaibhav", "Oracle123");
System.out.println("Connection established successfully!");
stmt = con.createStatement();
//execute insert query
145
ADVANCE JAVA
9.4 Conclusion
JDBC play role like a driver to move an object from one place to another by using
java platform. This chapter explained the knowledge about JDBC architecture and
some database programs.
146
Chapter 10: Spring - Getting Started with Spring Boot
Module 2
10
SPRING
GETTING STARTED WITH SPRING BOOT
Unit Structure
10.0 Objectives
10.1 Introduction
10.2 An Overview
10.2.1 Spring Boot Benefits
10.2.2 What’s the difference between Spring Boot and Spring MVC
10.2.3 Spring Boot Staters
10.2.4 Advantages
10.2.5 Disadvantages
10.3 Spring Boot and Database
10.3.1 JDBC connection pooling
10.3.2 Why do we need connection pooling
10.4 Spring Boot Web Application Development
10.4.1 Ease of Dependency Management
10.4.2 Automatic Configuration
10.4.3 Native Support for Application Server Servlet container
10.5 Spring Boot RESTful Web Services
10.5.1 Why REST is popular
10.5.2 Spring Boot REST example
10.6 conclusion
10.7 List of references
10.0 Objectives
The primary goals of Spring Boot are:
147
ADVANCE JAVA
148
Chapter 10: Spring - Getting Started with Spring Boot
10.2.2 What's the Difference Between Spring Boot and Spring MVC?
• The major differences between Spring Boot and Spring MVC come down to
differences between context and overall scale.
• Spring MVC is a specific Spring-based web framework in a traditional sense.
That means it requires manual build configurations, specifying dependencies
separately, and the use an application server.
• Spring Boot, on the other hand, is more like a module of Spring designed to
package Spring applications or frameworks with automation and defaults.
• So in theory one could have a Spring MVC project packaged as a Spring Boot
application. Both can be classified as Spring frameworks however the scale
of Spring Boot encompasses many types of Spring frameworks. While,
Spring MVC on the other hand specifies the design of the framework.
10.2.3 Spring Boot Staters
• Spring Boot starters were built to address exactly this problem. Starter POMs
are a set of convenient dependency descriptors that you can include in your
application. You get a one-stop-shop for all the Spring and related technology
that you need, without having to hunt through sample code and copy-paste
loads of dependency descriptors.
➢ The Web Starter
• First, let's look at developing the REST service; we can use libraries
like Spring MVC, Tomcat and Jackson – a lot of dependencies for a
single application.
• Spring Boot starters can help to reduce the number of manually adde d
dependencies just by adding one dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
149
ADVANCE JAVA
• For testing we usually use the following set of libraries: Spring Test,
JUnit, Hamcrest, and Mockito. We can include all of these libraries
manually, but Spring Boot starter can be used to automatically include
these libraries in the following way:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
• Notice that you don't need to specify the version number of an artifact.
Spring Boot will figure out what version to use – all you need to specify
is the version of spring-boot-starter-parent artifact. If later on you need
to upgrade the Boot library and dependencies, just upgrade the Boot
version in one place and it will take care of the rest.
➢ There are two ways to test the controller:
• Most web applications have some sort of persistence – and that's quite
often JPA.
Instead of defining all of the associated dependencies manually – let's go with
the starter instead:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
150
Chapter 10: Spring - Getting Started with Spring Boot
Notice that out of the box we have automatic support for at least the following
databases: H2, Derby and Hsqldb.
➢ The Mail Starter
• Spring boot may include dependencies that are not used thereby causing
huge deployment file size.
• Turning legacy spring applications into Spring boot requires a lot of effort
and a time-consuming process.
• Limited control of your application.
10.3 Spring Boot And Database
Spring Boot JDBC provides starter and libraries for connecting an application
with JDBC.
10.3.1 JDBC Connection Pooling
Connection pooling is a mechanism to create and maintain a collection of JDBC
connection objects. The primary objective of maintaining the pool of connection
151
ADVANCE JAVA
152
Chapter 10: Spring - Getting Started with Spring Boot
• The database server initializes the connection object and returns back to the
JDBC client (again, going through the same process).
• This is just an overview of what actually goes on behind the scenes. Rest
assured, the actual process is more complicated and elaborate than this. In a
single-threaded controlled environment, database transactions are mostly
linear, like opening a connection, doing database transaction, and closing the
connection when done. Real-life applications are more complex; the
mechanism of connection pooling can add to the performance although there
are many other properties that are critical to overall performance of the
application.
153
ADVANCE JAVA
You don’t need to specify the version as Spring Boot uses the default version
specified in the parent POM.
2. Specify Data Source Properties
Next, you need to specify the following properties in the Spring Boot
application configuration file (application.properties):
spring.datasource.url=jdbc:mysql://localhost:3306/bookshop
spring.datasource.username=root
spring.datasource.password=password
Update the data source URL, username and password according to your
MySQL configuration. If you connect to a remote MySQL server, you need
to replace localhost by IP address or hostname of the remote host.
154
Chapter 10: Spring - Getting Started with Spring Boot
155
ADVANCE JAVA
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String email;
private String password;
// getters and setters...
}
And declare a corresponding repository interface:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer> {
}
And then you can use the repository in a Spring MVC controller or business class
like this:
@Controller
public class UserController {
@Autowired
private UserRepository repo;
@GetMapping("/users")
public String listAll(Model model) {
List<User> listUsers = repo.findAll();
model.addAttribute("listUsers", listUsers);
return "users";
}
}
10.4.1 Ease of Dependency Management
156
Chapter 10: Spring - Getting Started with Spring Boot
project and you’ll be done (no need to look for compatible Hibernate database
drivers and libraries).
• If you want to create a Spring web application, just add the spring-boot-
starter-web dependency, which will pull all the libraries you need to develop
Spring MVC applications into your project, such as spring-webmvc, jackson-
json, validation-api, and Tomcat.
• To say in a few words what is Spring Boot used for, it collects all common
dependencies and defines them in one place, which allows developers to get
to work right away instead of reinventing the wheel every time they create a
new application.
• Therefore, the pom.xml file contains much fewer lines when used in Spring
Boot than in regular Spring.
10.4.2 Automatic Configuration
• One of the advantages of Spring Boot, that is worth mentioning is automatic
configuration of the application.
• After choosing a suitable starter package, Spring Boot will try to
automatically configure your Spring application based on
the jar dependencies you added. For example, if you add Spring-boot-starter-
web, Spring Boot will automatically configure registered beans such
as DispatcherServlet, ResourceHandlers, and MessageSource.
• If you are using spring-boot-starter-jdbc, Spring Boot automatically registers
the DataSource, EntityManagerFactory, and TransactionManager beans and
reads the database connection information from
the application.properties file.
• If you are not going to use a database and do not provide any details about
connecting manually, Spring Boot will automatically configure the database
in the memory without any additional configuration on your part (if you have
H2 or HSQL libraries). Automatic configuration can be completely
overridden at any time by using user preferences.
10.4.3 Native Support for Application Server – Servlet Container
• Every Spring Boot application includes an embedded web server. Developers
no longer have to worry about setting up a servlet container and deploying an
application to it. The application can now run itself as an executable jar file
using the built-in server. If you need to use a separate HTTP server, simply
exclude the default dependencies. Spring Boot provides separate starter
packages for different HTTP servers.
157
ADVANCE JAVA
158
Chapter 10: Spring - Getting Started with Spring Boot
• It does not define the standard message exchange format. We can build
REST services with both XML and JSON. JSON is more popular format
with REST. The key abstraction is a resource in REST. A resource can be
anything. It can be accessed through a Uniform Resource Identifier (URI).
10.5.1 Why REST is popular:
1. It allows the separation between the client and the server.
2. It doesn’t rely on a single technology or programming language.
3. You can build the scalable application or even integrate two different
applications using REST APIs
4. REST is stateless and uses basic HTTP methods like GET, PUT, POST, and
DELETE, etc. for communication between client and server.
➢ The resource has representations like XML, HTML, and JSON. The current
state capture by representational resource. When we request a resource, we
provide the representation of the resource. The important methods of HTTP
are:
GET: It reads a resource.
PUT: It updates an existing resource.
POST: It creates a new resource.
DELETE: It deletes the resource.
For example, if we want to perform the following actions in the social media
application, we get the corresponding results.
POST /users: It creates a user.
GET /users/{id}: It retrieves the detail of a user.
GET /users: It retrieves the detail of all users.
DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.
POST / users/{id}/ posts: It creates a post of the user.
159
ADVANCE JAVA
Rest Controller
The @RestController annotation is used to define the RESTful web services. It
serves JSON, XML and custom response. Its syntax is shown below −
@RestController
public class ProductServiceController {
}
Request Mapping
The @RequestMapping annotation is used to define the Request URI to access
the REST Endpoints. We can define Request method to consume and produce
object. The default request method is GET.
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
Request Body
The @RequestBody annotation is used to define the request body content type.
public ResponseEntity<Object> createProduct(@RequestBody Product product)
{
}
Path Variable
The @PathVariable annotation is used to define the custom or dynamic request
URI. The Path variable in request URI is defined as curly braces {} as shown below
−
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
}
Request Parameter
The @RequestParam annotation is used to read the request parameters from the
Request URL. By default, it is a required parameter. We can also set default value
for request parameters as shown here −
public ResponseEntity<Object> getProduct(
@RequestParam(value = "name", required = false, defaultValue = "honey")
String name) {
}
GET API
The default HTTP request method is GET. This method does not require any
Request Body. You can send request parameters and path variables to define the
custom or dynamic URL.
160
Chapter 10: Spring - Getting Started with Spring Boot
POST API
The HTTP POST request is used to create a resource. This method contains the
Request Body. We can send request parameters and path variables to define the
custom or dynamic URL.
PUT API
The HTTP PUT request is used to update the existing resource. This method
contains a Request Body. We can send request parameters and path variables to
define the custom or dynamic URL.
6.5.2 Spring Boot REST Example
To create the Spring Boot REST program, you have to follow below four steps:
1. Create a new project using the Spring Tool Suite or Spring Initializr Project.
2. Add dependencies in the Maven POM file.
3. Add a controller and expose REST APIs.
4. Add a service layer to communicate with Spring Data JPA’s CrudRepository
interface.
Create a new Spring Boot Project
161
ADVANCE JAVA
162
Chapter 10: Spring - Getting Started with Spring Boot
163
ADVANCE JAVA
164
Chapter 10: Spring - Getting Started with Spring Boot
[INFO] | \- org.springframework:spring-aspects:jar:5.1.8.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-
web:jar:2.1.6.RELEASE:compile
[INFO] | +- org.springframework.boot:spring-boot-
starter:jar:2.1.6.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-
logging:jar:2.1.6.RELEASE:compile
[INFO] | | | +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] | | | | \- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] | | | +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.11.2:compile
[INFO] | | | | \- org.apache.logging.log4j:log4j-api:jar:2.11.2:compile
[INFO] | | | \- org.slf4j:jul-to-slf4j:jar:1.7.26:compile
[INFO] | | +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] | | \- org.yaml:snakeyaml:jar:1.23:runtime
[INFO] | +- org.springframework.boot:spring-boot-starter-
json:jar:2.1.6.RELEASE:compile
[INFO] | | +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.9:compile
[INFO] | | | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] | | | \- com.fasterxml.jackson.core:jackson-core:jar:2.9.9:compile
[INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-
jdk8:jar:2.9.9:compile
[INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-
jsr310:jar:2.9.9:compile
[INFO] | | \- com.fasterxml.jackson.module:jackson-module-parameter-
names:jar:2.9.9:compile
[INFO] | +- org.springframework.boot:spring-boot-starter-
tomcat:jar:2.1.6.RELEASE:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.21:compile
[INFO] | | +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.21:compile
[INFO] | | \- org.apache.tomcat.embed:tomcat-embed-
websocket:jar:9.0.21:compile
[INFO] | +- org.hibernate.validator:hibernate-validator:jar:6.0.17.Final:compile
[INFO] | | \- javax.validation:validation-api:jar:2.0.1.Final:compile
[INFO] | +- org.springframework:spring-web:jar:5.1.8.RELEASE:compile
[INFO] | \- org.springframework:spring-webmvc:jar:5.1.8.RELEASE:compile
165
ADVANCE JAVA
[INFO] | \- org.springframework:spring-
expression:jar:5.1.8.RELEASE:compile
[INFO] +- com.h2database:h2:jar:1.4.199:runtime
[INFO] +- org.springframework.boot:spring-boot-starter-
test:jar:2.1.6.RELEASE:test
[INFO] | +- org.springframework.boot:spring-boot-test:jar:2.1.6.RELEASE:test
[INFO] | +- org.springframework.boot:spring-boot-test-
autoconfigure:jar:2.1.6.RELEASE:test
[INFO] | +- com.jayway.jsonpath:json-path:jar:2.4.0:test
[INFO] | | \- net.minidev:json-smart:jar:2.3:test
[INFO] | | \- net.minidev:accessors-smart:jar:1.2:test
[INFO] | | \- org.ow2.asm:asm:jar:5.0.4:test
[INFO] | +- junit:junit:jar:4.12:test
[INFO] | +- org.assertj:assertj-core:jar:3.11.1:test
[INFO] | +- org.mockito:mockito-core:jar:2.23.4:test
[INFO] | | +- net.bytebuddy:byte-buddy-agent:jar:1.9.13:test
[INFO] | | \- org.objenesis:objenesis:jar:2.6:test
[INFO] | +- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] | +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] | +- org.skyscreamer:jsonassert:jar:1.5.0:test
[INFO] | | \- com.vaadin.external.google:android-
json:jar:0.0.20131108.vaadin1:test
[INFO] | +- org.springframework:spring-core:jar:5.1.8.RELEASE:compile
[INFO] | | \- org.springframework:spring-jcl:jar:5.1.8.RELEASE:compile
[INFO] | +- org.springframework:spring-test:jar:5.1.8.RELEASE:test
[INFO] | \- org.xmlunit:xmlunit-core:jar:2.6.2:test
[INFO] \- org.springframework.boot:spring-boot-
devtools:jar:2.1.6.RELEASE:runtime (optional)
[INFO] +- org.springframework.boot:spring-boot:jar:2.1.6.RELEASE:compile
[INFO] \- org.springframework.boot:spring-boot-
autoconfigure:jar:2.1.6.RELEASE:compile
Controller to expose REST APIs
For this tutorial, we will CRUD APIs for User Management System.
By using these APIs we can add, retrieve, update, or delete the user details from
the database.
166
Chapter 10: Spring - Getting Started with Spring Boot
167
ADVANCE JAVA
@PutMapping("/update/{id}")
public User addOrUpdateUserById(@RequestBody User user,
@PathVariable("id") int id) {
return mService.addOrUpdateUserById(user, id);
}
@DeleteMapping("/delete/{id}")
public void deleteUser(@PathVariable("id") int id) {
mService.deleteUser(id);
}
}
Service layer:
The service layer acts as an intermediate layer between a controller and a
repository class.
package com.codedelay.rest.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.codedelay.rest.dao.UserRepository;
import com.codedelay.rest.entity.User;
import com.codedelay.rest.exception.UserNotFoundException;
@Service
public class UserManageService {
@Autowired
private UserRepository mRepository;
public Iterable<User> getAllUsers() {
return mRepository.findAll();
}
public User addUser(User user) {
return mRepository.save(user);
}
public User findUserById(int id) {
return mRepository.findById(id).get();
}
168
Chapter 10: Spring - Getting Started with Spring Boot
169
ADVANCE JAVA
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Write the Repository Interface.
package com.codedelay.rest.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.codedelay.rest.entity.User;
public interface UserRepository extends CrudRepository<User, Integer> {
}
UserRepository interface extends CrudRepository.
CrudRepository is a magical interface from Spring Data JPA.
It allows writing simple CRUD functions without writing a single line of code.
Exception handling in Spring Boot REST
A good REST API also covers exception scenarios.
Let discuss one simple scenario.
What will happen if HTTP GET /find/{id} doesn’t find a particular user in the
database?
It should throw an exception. Isn’t it?
Let’s add one more class UserNotFoundException class in
com.codedelay.rest.exception package.
170
Chapter 10: Spring - Getting Started with Spring Boot
package com.codedelay.rest.exception;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(int id) {
super("User id not found : " + id);
}
}
Now add the Service class to throw the UserNotFoundException exception if
there are no user details available in the database for that particular user id.
public User findUserById(int id) {
return mRepository.findById(id).orElseThrow(() -> new
UserNotFoundException(id));
}
It is not sufficient to throw java exception.
We have to return some HTTP error when UserNotFoundException occurs.
For this, let’s create a class GlobalExceptionHandler which will return
HttpStatus.NOT_FOUND error when UserNotFoundException occurs.
package com.codedelay.rest.exception;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public void handleUserNotFoundError(HttpServletResponse response) throws
IOException {
response.sendError(HttpStatus.NOT_FOUND.value());
}
}
10.6 Conclusion
Spring Boot has become an integral part of the Java ecosystem, offering an
efficient and scalable toolbox for building Spring applications with a
microservices architecture. It speeds up the development and deployment
171
ADVANCE JAVA
processes by using intuitive default settings for unit and integration tests. What’s
more, Spring Boot helps developers build robust applications with clear and
secure configurations without spending a lot of time and effort on figuring out the
intricacies of Spring. If you’re not sure about whether or not you should use this
solution for your Java project, carefully review the pros and cons of using Spring
Boot, its core features, and see how they align with your business goals.
Alternatively, you can entrust a reliable software vendor with the development
process.
172
Chapter 11: Understanding Transaction Management in Spring
Module 2
11
UNDERSTANDING TRANSACTION
MANAGEMENT IN SPRING
Unit Structure
11.0 Objectives
11.1 Introduction
11.2 An Overview
11.2.1 Transaction Propagation (Required)
11.2.2 Transaction Propagation (Supports)
11.2.3 Transaction Propagation (Not_Supported)
11.2.4 Transaction Propagation (Requires_New)
11.2.5 Transaction Propagation (Never)
11.2.6 Transaction Propagation (Mandatory)
11.3 Conclusion
11.4 List of References
11.0 Objectives
173
ADVANCE JAVA
11.1 Introduction
A transaction is an action or series of actions that are being performed by a single
user or application program, which reads or updates the contents of the database.
A transaction can be defined as a logical unit of work on the database. This may be
an entire program, a piece of a program, or a single command (like the SQL
commands such as INSERT or UPDATE), and it may engage in any number of
operations on the database. In the database context, the execution of an application
program can be thought of as one or more transactions with non-database
processing taking place in between.
In traditional relational database design, transactions are completed by COMMIT
or ROLLBACK SQL statements, which indicate a transaction’s beginning or end.
The ACID acronym defines the
properties of a database transaction, as follows:
• Atomicity: A transaction must be fully complete, saved (committed) or
completely undone (rolled back). A sale in a retail store database illustrates a
scenario which explains atomicity, e.g., the sale consists of an inventory
reduction and a record of incoming cash. Both either happen together or do
not happen—it's all or nothing.
• Consistency: The transaction must be fully compliant with the state of the
database as it was prior to the transaction. In other words, the transaction
cannot break the database’s constraints. For example, if a database table’s
Phone Number column can only contain numerals, then consistency dictates
that any transaction attempting to enter an alphabetical letter may not
commit.
174
Chapter 11: Understanding Transaction Management in Spring
11.2 An Overview
175
ADVANCE JAVA
➢ As the Employee Service may also be called directly we will need to use
Transaction annotation with Employee Service also. So both the services —
Organization Service and the Employee Service will be using Transaction
annotation.
➢ We will be looking at the various propagation scenarios by observing the
behaviour of the Organization and Employee service.There are six types of
Transaction Propagations-
1) REQUIRED
2) SUPPORTS
3) NOT_SUPPORTED
4) REQUIRES_NEW
5) NEVER
6) MANDATORY
13.2.1 Transaction Propagation (Required):
176
Chapter 11: Understanding Transaction Management in Spring
Here both the Organization Service and the Employee Service have the transaction
propagation defined as Required. This is the default Transaction Propagation.
Code-
The Organization Service will be as follows-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.model.Employee;
import com.javainuse.model.EmployeeHealthInsurance;
import com.javainuse.service.EmployeeService;
import com.javainuse.service.HealthInsuranceService;
import com.javainuse.service.OrganizationService;
@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee,
EmployeeHealthInsurance employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test
transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthI
nsurance);
}
@Override
public void leaveOrganization(Employee employee,
EmployeeHealthInsurance employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHea
lthInsurance.getEmpId());
177
ADVANCE JAVA
}
}
The Employee Service will be as follows-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.dao.EmployeeDao;
import com.javainuse.model.Employee;
import com.javainuse.service.EmployeeService;
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
@Override
public void deleteEmployeeById(String empid) {
employeeDao.deleteEmployeeById(empid);
}
}
Output:
178
Chapter 11: Understanding Transaction Management in Spring
Here both the Organization Service has the transaction propagation defined
as Required while Employee Service the transaction propagation is defined
as Supports.
Code-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.model.Employee;
import com.javainuse.model.EmployeeHealthInsurance;
import com.javainuse.service.EmployeeService;
import com.javainuse.service.HealthInsuranceService;
import com.javainuse.service.OrganizationService;
179
ADVANCE JAVA
@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsura
nce);
}
@Override
public void leaveOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHealthIns
urance.getEmpId());
}
}
The Employee Service will be as follows-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.dao.EmployeeDao;
import com.javainuse.model.Employee;
import com.javainuse.service.EmployeeService;
@Service
@Transactional(propagation=Propagation.SUPPORTS)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
180
Chapter 11: Understanding Transaction Management in Spring
@Override
public void deleteEmployeeById(String empid) {
employeeDao.deleteEmployeeById(empid);
}
}
Output:
181
ADVANCE JAVA
Here for the Organization Service we have defined the transaction propagation
as REQUIRED and the Employee Service have the transaction propagation defined
as NOT_SUPPORTED
Code-
The Organization Service will be as follows-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.model.Employee;
import com.javainuse.model.EmployeeHealthInsurance;
import com.javainuse.service.EmployeeService;
import com.javainuse.service.HealthInsuranceService;
import com.javainuse.service.OrganizationService;
@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsura
nce);
}
@Override
public void leaveOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHealthIns
urance.getEmpId());
}
}
182
Chapter 11: Understanding Transaction Management in Spring
183
ADVANCE JAVA
Here for the Organization Service we have defined the transaction propagation
as REQUIRED and the Employee Service have the transaction propagation defined
as REQUIRES_NEW
Code-
184
Chapter 11: Understanding Transaction Management in Spring
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsuran
ce);
}
@Override
public void leaveOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHealthInsu
rance.getEmpId());
}
}
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.dao.EmployeeDao;
import com.javainuse.model.Employee;
import com.javainuse.service.EmployeeService;
@Service
@Transactional(propagation=Propagation.REQUIRES_NEW)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
185
ADVANCE JAVA
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
@Override
public void deleteEmployeeById(String empid) {
employeeDao.deleteEmployeeById(empid);
}
}
Output:
186
Chapter 11: Understanding Transaction Management in Spring
Here for the Organization Service we have defined the transaction propagation
as REQUIRED and the Employee Service have the transaction propagation defined
as NEVERs
Code-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.model.Employee;
import com.javainuse.model.EmployeeHealthInsurance;
import com.javainuse.service.EmployeeService;
import com.javainuse.service.HealthInsuranceService;
import com.javainuse.service.OrganizationService;
@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance
187
ADVANCE JAVA
employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsuran
ce);
}
@Override
public void leaveOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHealthInsu
rance.getEmpId());
}
}
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.dao.EmployeeDao;
import com.javainuse.model.Employee;
import com.javainuse.service.EmployeeService;
@Service
@Transactional(propagation=Propagation.NEVER)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
@Override
public void deleteEmployeeById(String empid) {
employeeDao.deleteEmployeeById(empid);
}
}
188
Chapter 11: Understanding Transaction Management in Spring
Output:
Here for the Organization Service we have defined the transaction propagation
as REQUIRED and the Employee Service have the transaction propagation defined
as MANDATORY
189
ADVANCE JAVA
Code-
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.model.Employee;
import com.javainuse.model.EmployeeHealthInsurance;
import com.javainuse.service.EmployeeService;
import com.javainuse.service.HealthInsuranceService;
import com.javainuse.service.OrganizationService;
@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.insertEmployee(employee);
if (employee.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing exception to test transaction rollback");
}
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsuran
ce);
}
@Override
public void leaveOrganization(Employee employee, EmployeeHealthInsurance
employeeHealthInsurance) {
employeeService.deleteEmployeeById(employee.getEmpId());
healthInsuranceService.deleteEmployeeHealthInsuranceById(employeeHealthInsu
rance.getEmpId());
}
}
package com.javainuse.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
190
Chapter 11: Understanding Transaction Management in Spring
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.javainuse.dao.EmployeeDao;
import com.javainuse.model.Employee;
import com.javainuse.service.EmployeeService;
@Service
@Transactional(propagation=Propagation.MANDATORY)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
@Override
public void deleteEmployeeById(String empid) {
employeeDao.deleteEmployeeById(empid);
}
}
Output:
191
ADVANCE JAVA
11.3 Conclusion
https://docs.spring.io/spring-framework/docs/2.5.x/reference/transaction.htmls
https://medium.com/@rameez.s.shaikh/spring-boot-transaction-tutorial-
understanding-transaction-propagation-ad553f5d85d4
❖❖❖❖❖
192