0% found this document useful (0 votes)
16 views155 pages

Advance Java (NOTES)

This document discusses multi-threading concepts in Java. It defines multitasking as performing more than one task at a time, which can be achieved through either multiprocessing (executing multiple processes simultaneously) or multithreading (executing multiple threads simultaneously). There are two ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. The life cycle of a thread involves phases like started, running, waiting, and ended. Multiple threads can run concurrently by being allocated separate call stacks and switching between stacks via a thread scheduler.

Uploaded by

dhirajzope015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views155 pages

Advance Java (NOTES)

This document discusses multi-threading concepts in Java. It defines multitasking as performing more than one task at a time, which can be achieved through either multiprocessing (executing multiple processes simultaneously) or multithreading (executing multiple threads simultaneously). There are two ways to create threads in Java: by extending the Thread class or implementing the Runnable interface. The life cycle of a thread involves phases like started, running, waiting, and ended. Multiple threads can run concurrently by being allocated separate call stacks and switching between stacks via a thread scheduler.

Uploaded by

dhirajzope015
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 155

J2EE-NOTES

MULTI-THREADING
------------------------------------------------------------------------------------------
• Two understand the concept of multi-threading : We first need to understand what
is multitasking and what is multiprocessing ?

➢ Multitasking :-
1. Performing or executing more than one task at the same time is called as
multitasking
2. Task is the end goal that has to be achieved
3. Task is the combination of more than one process
4. Task is used to increase the performance of process

➢ Types of multitasking / how to achieve multitasking ?


• There is two ways or types to achieve multitasking,
a. Process based multitasking i.e. multiprocessing
b. Thread base multi-tasking i.e. multithreading

a. Process based multitasking that is multiprocessing :-


1. Performing or executing more than one process at the same time is called as
multiprocessing
2. Process are the steps involved in the completion of task
3. Process can be called as combination of more than one thread
4. Multiprocessing is best suitable at the system level or operating system

P1 P2 P3 T1 T2 T3

P1 P2 P3 T4 T5 T6

P1 P2 P3 T7 T8 T9

Task Process
b. Thread based multitasking i.e. multithreading :-
1. Thread is the smallest unit of process
2. Executing or implementing more than one thread at the same time is called as
multithreading
3. Multithreading is the best suitable for programming level
4. multi threading is used to create softwares, animation, creating games and so on.

TILOTTAM ZOPE 1
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
➢ Threads in Java :-
• In Java thread is a special class that can be created in two ways ,
a. extend thread i.e. thread class
b. implements runnable

Ex., extends Thread

public class mythread1

implements runnable

➢ life cycle in thread :- {IMP for Interview}

Running

Start End

Wait

1. Start To Running :-

Start When a thread is initialized and the


resources required for a thread execution are
allocated to it then the thread moves from
Running start phase to running phase

2. Start to Wait :-

Start When a thread is initialized and the


resources are not required for its execution
are allocated to it then the thread moves
Wait from start phase to end phase

TILOTTAM ZOPE 2
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
3. Running to Wait :-

Running If a thread is already in running phase and


the resources is allocated to it are taken
away then the thread moves from running
Wait phase to wait phase

4. Wait to Running :-

Wait If the thread is in waiting phase and the


resources required for its execution are
allocated to it then the thread moves from
Running wait to running phase

5. Running to End :-

Running If a thread is running phase and complete its


execution then the thread moves from
running phase to end phase
Wait

6. Wait to End :-
If a thread is in wait phase and the resources
Wait required for its execution are not allocated to
it for a long time then the thread moves from
wait phase to end phase
End

NOTE :-
• The life cycle phases of thread are represented as methods of the thread.

TILOTTAM ZOPE 3
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
➢ Ways to creating threads :-
1. By using extends thread
2. By using implements runnable

1. By using extends thread :-


• MyThread1.java :-
package com.jspiders.multihtreading.thread ;
public class Mythread1 extends Thread{
@override
public void run(){
sopln(“Mythread1 is now running”)
}
}

• ThreadMain.java :-
package com.jspiders.multihtreading.main ;
import com.jspiders.multithreading.thread.Mythread1 ;
public class ThreadMain{
p. s. v. m (S[] a){
Mythread1 mythread1 = new Mythread1() ;
mythread1.start() ;
}
}

❖ start() :-
1. It is a non static method present in thread class
2. It is used to start a class object as a thread
3. The start() will implicitly call the run() from the target class

❖ run() :-
1. The behaviour (Execution Logic) of the thread is defined in the run()
2. It is also non static method present inside the runnable interface

TILOTTAM ZOPE 4
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
2. By using implements runnable :-
• MyThread2.java :-
package com.jspiders.multihtreading.thread ;
public class Mythread1 extends Thread{
@override
public void run(){
sopln(“Mythread2 is now running”)
}
}

• ThreadMain.java :-
package com.jspiders.multihtreading.main ;
import com.jspiders.multithreading.thread.Mythread2 ;
public class ThreadMain{
p. s. v. m (S[] a){
Mythread2 mythread2 = new Mythread2() ;
Thread thread = new Thread(MyThread2)
thread.start() ;
}
}

a. In this case, As there is no direct relationship between MyThread2 class and


Thread class hence it is not possible to use start() with the help of MyThread2
class object reference variable
b. Thats why, We need to create the object of thread class and pass the object of
MyThread2 as the argument to overloaded thread class constructor
c. This causes, The thread class object to ignore its own behaviour and accept the
behaviour of MyThread2 class object

➢ Executing multiple threads at a time :-


When more than one thread are implemented in same application each trade is
allocated separate stack area for its execution the control is transferred between the
stack which is done by component called as ThreadScheduler

TILOTTAM ZOPE 5
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
• MyThread1.java :-
package com.jspiders.multithreading.thread;
public class MyThread1 extends Thread {

@Override
public void run() {
for(int i=1; i<=5; i++) {
System.out.println("MyThread 1 is now running");
}
}
}

• MyThread2.java :-
package com.jspiders.multithreading.thread;
public class MyThread2 implements Runnable {

@Override
public void run() {
for(int i= 1; i<=5; i++) {
System.out.println("MyThread 2 is now running");
}
}
}

• ThreadMain.java :-
package com.jspiders.multihtreading.main ;
import com.jspiders.multithreading.thread.Mythread2 ;
import com.jspiders.multithreading.thread.Mythread2 ;
public class ThreadMain{
p. s. v. m (S [] a) {
Mythread1 mythread1 = new Mythread1() ;
Mythread2 mythread2 = new Mythread2() ;
Thread thread = new Thread (Mythread2)
MyThread1.start();
}
}

TILOTTAM ZOPE 6
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
a. the actual output might differ from the expected output it is depending on the
transfer of controller between the stack for the thread done by ThreadScheduler

➢ Thread scheduler :-
1. It is the component in multithreading which is responsible to manage and control
the execution of multiple threads
2. It is also responsible to create a dedicated stack for each thread and the transferred
control between the stacks based on the thread properties.

➢ Thread properties :-
1. Each thread has properties on its own i.e. are as follows ;
a. name
b. priority

2. These properties can be access and modified with the help of getters and setters
methods

getName() getPriority()
a. name b. priority

setName(“String”) setPriority(int)

QUE. why we need multithreading ?


→ A class in which there are small task, we have to executes them together at a
time

QUE. can we invoke the thread again ? If not then what type of execution will
provide (compile time exception or run time exception) ?
→No, we cannot invoke the trade again once the thread ends it will not be
executed again if we do so then it will get illegal thread exception

➢ ways to create thread properties :-


a. By using thread class
b. By using implements runnable

TILOTTAM ZOPE 7
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
a. By using thread class :-
• MyThread1.java :-
package com.jspiders.multithreadingproperties.thread;
public class MyThread1 extends Thread {
@Override
public void run() {
System.out.println
("The name of the thread is " + this.getName());
System.out.println
("The priority of the thread is " + this.getPriority());
}
}
• ThreadMain.java :-
package com.jspiders.multithreadingproperties.main;
import com.jspiders.multithreadingproperties.thread.MyThread;
import com.jspiders.multithreadingproperties.thread.MyThread1;
public class ThreadMain {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName("Thread1");
myThread.setPriority(3);
MyThread1 myThread1 = new MyThread1();
Thread thread = new Thread(myThread1);
thread.setName("Thread2");
thread.setPriority(5);
myThread.start();
thread.start();
}
}
❖ getName() :-
It is a non static method present inside the thread class which is used to restrict the
name of the thread

❖ setName() :-
1. It is a non static method present inside the thread class which is used to modify or
set the name for the class
2. It accept string argument

TILOTTAM ZOPE 8
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
❖ getPriority() :-
It is a non static method present inside the thread class which is used to restrive the
value of the thread

❖ setPriority() :-
1. It is a non static method present inside the thread class which is used to modify or
set the priority for the thread
2. It accepts int argument

b. By using implements runnable :-


• MyThread2.java :-
package com.jspiders.multithreadingproperties.thread;
public class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println
("The name of the thread is "
+ Thread.currentThread().getName());
System.out.println
("The priority of the thread is "
+ Thread.currentThread().getPriority());
}
}

• ThreadMain.java :-
package com.jspiders.multithreadingproperties.main;
import com.jspiders.multithreadingproperties.thread.MyThread2;
public class ThreadMain2 {
public static void main(String[] args) {
MyThread2 myThread2 = new MyThread2();
myThread2.setPriority("Thread2");
Thread thread = new Thread(myThread2);
thread.setName("Thread2");
thread.setPriority(8);
thread.start();
}

TILOTTAM ZOPE 9
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
}

➢ Executing multiple thread at a time :-


package com.jspiders.multithreadingproperties.main;
import com.jspiders.multithreadingproperties.thread.MyThread1;
import com.jspiders.multithreadingproperties.thread.MyThread2;
public class ThreadMain2 {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
myThread1.setName(“Tilottam”)
myThread1.setPriority(8)
MyThread2 myThread2 = new MyThread2();
myThread2.setPriority("Thread2");
Thread thread = new Thread(myThread2);
thread.setName("Udhav");
thread.setPriority(10);
myThread1.start();
thread.start();
}
}

NOTE :-
• Again run the program after some time it will change the position of execution the
thread scheduler does till does not assign the order of execution based on the
thread priority as it is not configured

❖ currentThread() :-
1. It is a non static method present in thread class which is used to point towards the
current object of thread
2. It is generally used to when there is no direct relation between current class & the
thread class

❖ stop() :-
1. It is a non static method present inside the thread class which is used to stop the
execution of the curretly execution thread forcefully

TILOTTAM ZOPE 10
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
• MyThread3.java :-
package com.jspiders.multithreading.thread;
public class MyThread3 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
this.stop();
}
System.out.println(this.getName() + " is now running");
}
}
}
• ThreadMain3.java :-
package com.jspiders.multithreadingproperties.main;
import com.jspiders.multithreadingproperties.thread.MyThread;
import com.jspiders.multithreadingproperties.thread.MyThread1;
public class ThreadMain {
public static void main(String[] args) {
MyThread3 myThread3 = new MyThread3();
Thread thread = new Thread(myThread3);
thread.setName("Thread3");
thread.start();
}
}

NOTE :-
• The stop() is deprected in java

• Account.java :-
package com.jspiders.multithreading.resource;
public class Account {
double accountBalance;
public Account(double accountBalance) {
this.accountBalance = accountBalance;
}

TILOTTAM ZOPE 11
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
public double checkBalance() {
return this.accountBalance;
}
public void deposit(double amount) {
System.out.println("Depositing " + amount + " in the account");
accountBalance += amount;
System.out.println("Current balance : " + checkBalance());
}
public void withdraw(double amount) {
System.out.println("Withdrawing " + amount + " in the account");
accountBalance -= amount;
System.out.println("Current balance : " + checkBalance());
}
}

• Husband.java :-
package com.jspiders.multithreading.thread;
import com.jspiders.multithreading.resource.Account;
public class Husband extends Thread {
Account account;
public Husband(Account account) {
this.account = account;
}
@Override
public void run() {
account.deposit(1000);
account.withdraw(500);
}
}

• Wife.java :-
package com.jspiders.multithreading.thread;
import com.jspiders.multithreading.resource.Account;
public class Wife extends Thread {
Account account;
public Wife(Account account) {
this.account = account;

TILOTTAM ZOPE 12
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
}
@Override
public void run() {
account.deposit(500);
account.withdraw(5000);
}
}

• AccountMain :-
package com.jspiders.multithreading.main;
import com.jspiders.multithreading.resource.Account;
import com.jspiders.multithreading.thread.Husband;
import com.jspiders.multithreading.thread.Wife;
public class AccountMain {
public static void main(String[] args) {
Account account = new Account(10000);
Husband husband = new Husband(account);
Wife wife = new Wife(account);
husband.start();
wife.start();
}
}

NOTE :-
• Again execute program after some time it might be differ of actual output

a. When multiple thread operates on the same resource, all the thread will be
(unaware) of the operation performed by other thread on same resources
b. Each thread operates on the thread independently which reads to inconsistency in
data
c. In the above case, The husband thread and wife thread work performing deposit
and withdraw operation on the same object of the account class both the husband
and wife thread works unaware of each other operation on the account class object
this leads to inconsistant final account balance

TILOTTAM ZOPE 13
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
➢ Synchronization :-
1. It is a procedure to achieve the data consistency while executing multiple threads
that are operating on a shared resources
2. It can be achieved with the help of synchronized keyword
3. If synchronized keyword is used along with a resource then only one thread will be
allowed to access that resources at a time. It can be said that, If a resource is
synchronized then the thread will applied long on that resource while accessing it.
Rresource can’t be access unless a lock on the resource has been released

➢ Locks on multithreading :-
1. In multithreading there are two types of lock ;
a. object lock
b. class lock

❖ Shared resource :-
• The resources which is access by more than one threads is called a shared
resources

a. Object lock :-
1. If the synchronized shared resources is a non static member then the lock applied
on it will be object lock

b. class lock :-
1. If the synchronized shared resource is a static member then the lock applied on it
will be class lock
1 Apply Lock
T1 7 Apply Lock T4

2 Relesed Lock Synchornized 8 Relesed Lock


shared
Resource
3 Apply Lock 5 Apply Lock

T2 6 Relesed Lock T3
4 Relesed Lock

TILOTTAM ZOPE 14
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
• Account.java :-
package com.jspiders.multithreading.resource;
public class Account {
double accountBalance;
public Account(double accountBalance) {
this.accountBalance = accountBalance;
}
public double checkBalance() {
return this.accountBalance;
}
public synchronized void deposit(double amount) {
System.out.println("Depositing " + amount + " in the account");
accountBalance += amount;
System.out.println("Current balance : " + checkBalance());
}
public synchronized void withdraw(double amount) {
System.out.println("Withdrawing " + amount + " in the account");
accountBalance -= amount;
System.out.println("Current balance : " + checkBalance());
}
}

❖ wait() :-
It is a non static method present in the thread class which is used to forcefully &
move a thread from the running phase to the wait phase .

NOTE :-
• The thread which has been paused forcefully add move to the waiting phase, will
not resume its execution on its own

❖ notify() :-
It is a non static method present inside the thread class which is used to call the
waiting thread to resume thread

❖ notifyAll() :-
It is a non static method present inside the thread class which is used to call, all the
waiting threads to resume there execution .

TILOTTAM ZOPE 15
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
• Pizza.java :-
package com.jspiders.multithreadingwaitandnotify.resourse;
public class Pizza {
int noOfPizza;
public synchronized void orderPizza(int orderedPizza) {
System.out.println("Ordering " + orderedPizza + " pizzas");
if (orderedPizza > noOfPizza) {
System.out.println(orderedPizza + " pizzas not available");
System.out.println("Please wait..!!");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
noOfPizza -= orderedPizza;
System.out.println("Order of " + orderedPizza + " pizzas successfull.");
}
public synchronized void makePizza(int bakedPizza) {
System.out.println("Making " + bakedPizza + " pizzas");
noOfPizza += bakedPizza;
System.out.println(noOfPizza + " pizzas available");
this.notifyAll();
}
}

• Friends.java :-
package com.jspiders.multithreadingwaitandnotify.thread;
import com.jspiders.multithreadingwaitandnotify.resourse.Pizza;
public class Friends extends Thread {
private Pizza pizza;
public Friends(Pizza pizza) {
this.pizza = pizza;
}
@Override
public void run() {
pizza.orderPizza(5);

TILOTTAM ZOPE 16
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
}
}

• Dominos.java :-
package com.jspiders.multithreadingwaitandnotify.thread;
import com.jspiders.multithreadingwaitandnotify.resourse.Pizza;
public class Dominos extends Thread {
private Pizza pizza;
public Dominos(Pizza pizza) {
this.pizza = pizza;
}
@Override
public void run() {
pizza.makePizza(10);
}
}

• PizzaMain.java :-
package com.jspiders.multithreadingwaitandnotify.main;
import com.jspiders.multithreadingwaitandnotify.resourse.Pizza;
import com.jspiders.multithreadingwaitandnotify.thread.Dominos;
import com.jspiders.multithreadingwaitandnotify.thread.Friends;
public class PizzaMain {
public static void main(String[] args) {
Pizza pizza = new Pizza();
Friends friends1 = new Friends(pizza);
Friends friends2 = new Friends(pizza);
Dominos dominos = new Dominos(pizza);
friends1.start();
friends2.start();
dominos.start();
}
}

TILOTTAM ZOPE 17
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
➢ sleep() :-
1. It is an static method present in thread class which accepts a long variable as an
argument
2. The sleep() is similar to wait() i.e. which is used to pause the execution of
currently executing thread forcefully & move the thread from running to wait
phase
3. Unlike wait() , sleep() doesn’t need a notify() call the thread will resume with its
execution on its own after a specific amount time
4. The int argument is considered as time in milisec.

• SleepDemo.java :-
package com.jspiders.multithreadingsleep.main;
public class SleepDemo {
public static void main(String[] args) {
String message = "This is the magic of sleep()";
char[] messageArray = message.toCharArray();
for (int i = 0; i < message.length(); i++) {
System.out.print(messageArray[i]);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

➢ Comparision between Wait() & Sleep() :-


No. wait() sleep()
It is a non static method present It is static method present in
1.
in thread class thread class
It accepts a long variable as a
2. It doesn’t accept any argument
argument
It is also throws
3. It throws InterruptedException
InterruptedException
It is used to forcefully pause a It is used to forcefully pause a
4.
thread thread

TILOTTAM ZOPE 18
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
notify() call is mandatory notify() call is not required to
5. required to call the waiting call the waiting thread to
thread to resume its execution resume its execution
The waiting thread will
The waiting thread will not
resume its execution on its
6. resume its execution on its own
own after specific time

➢ Daemon threads :-
1. If a thread is created by extending thread class or implementing runnable interface
then search thread is called as user created or user defined thread.
2. The user defined threads have to be called for execution by the programmer.
3. In Java, there are some predefined threads that are of low priority and are called for
execution implicitly by the JVM. the programmer is not responsible to call such
predefined threads for execution.
4. These predefined threads are called as daemon thread
5. One of the most important daemon thread is “Garbage Collection”

➢ Garbage Collection :-
1. The garbage collection daemon thread is responsible for removing garbage values
from the memory
2. As soon as a garbage value is dedicated the JVM calls the garbage collection for
execution
3. Garbage collection is required in 2 situations,
a. after deriffering an object
b. after nullifying an object

memory
A a = new A();

@100 X a = null
garbage
collected
nullifying

TILOTTAM ZOPE 19
J2EE-NOTES
MULTI-THREADING
------------------------------------------------------------------------------------------
garbage
collected
a
A a = new A() ;
b
A b = new A() ;
deriffering

➢ Advantages of garbage collection :-


1. Garbage collection makes java efficient in memory management.
2. Bcoz., of garbage collection deamon thread, the programmer does not need to
worry or take care of memory management

NOTE :-
• A user defined thread can be made to behave as a daemon thread with the help
of set daemon method it can be done by passing “ TRUE ” as an argument to
this method.

TILOTTAM ZOPE 20
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
➢ What is file ?
1. File is an entity where the data can be stored and where the data can be retrieved
2. There are two types of entity ,
a. source entity which is reading the data from the file
b. target entity which is writing the data to the file

➢ What is file handling & why file handling is required ?


1. Performing operation on a file such as reading and writing the data to a file is
known as file handling
2. File handling is an integral part of programming language which is enable to store
the output of any particular program in a file and allow to performing on it

➢ Operations on file :-
1. create a file
2. get info of file
3. delete a file
4. read from file
5. write a file

TILOTTAM ZOPE 21
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
➢ What is file class ?
1. In java we can performing operation on file with the help of file class which is
present inside Java dot io package
2. It is used to creating an object of class and then specifying the name of the file
3. File class is an overloaded constructor.
4. One of the Generally use constructor is as follows,

file(String path-name)

➢ PathName :-
1. The PathName value can accept the values in 2 different ways
2. The PathName consists of 2 parts i.e. the folder path and the file name
3. The PathName value can consist both the folder path with the file name but it can
also accept just the file name
4. The folder path can also be referred to as absolute path
5. The file will be created in the mention location only if the absolute path is
provided if absolute path is not provided then the file will be created in the default
location that is ( project folder )
• CreateFileDemo1.java :-
package com.jspiders.filehandling.create;
import java.io.File;
import java.io.IOException;
public class CreateFileDemo1 {
public static void main(String[] args) {
File file = new File("Hello.txt");
if (file.exists()) {
System.out.println("The file already exists.");
} else {
try {
file.createNewFile();
System.out.println("File created");
} catch (IOException e) {
System.out.println("File not created");
e.printStackTrace();
}
}
}

TILOTTAM ZOPE 22
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
}

• In the above case the absolute path is not mentioned hence the File will be created
in the default location itself

NOTE :-
• We must not create a file if it already exists

• CreateFileDemo2.java :-
package com.jspiders.filehandling.create;
import java.io.File;
import java.io.IOException;
public class CreateFileDemo2 {
public static void main(String[] args) {
File file = new File("D:/WEJA1/Hello.txt");
if (file.exists()) {
System.out.println("The file already exists.");
} else {
try {
file.createNewFile();
System.out.println("File created");
} catch (IOException e) {
System.out.println("File not created");
e.printStackTrace();
}
}
}
}

• In the above case , The file will be created in the mentioned location only as the
absolute path has been priovide.

❖ CreateNewFile() :-
It is a non static method present in the file class which is used to create a file
sysytem memory based on the mentioned absolute path & the file name

TILOTTAM ZOPE 23
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
❖ exists() :-
1. It is a non static method present in a file class which is used to check whether the
mentioned file exists in the sysytem memory or not
2. If the file exists then the method returns “TRUE”
3. If the file doen’t exists then the method returns “FALSE”

• DeleteFileDemo1.java :-
package com.jspiders.filehandling.delete;
import java.io.File;
public class DeleteFileDemo1 {
public static void main(String[] args) {
File file = new File("Hello.txt");
if (file.exists()) {
file.delete();
System.out.println("File deleted.");
} else {
System.out.println("File does not exist.");
}

}
}

• FileInfoDemo.java :-
package com.jspiders.filehandling.info;
import java.io.File;
public class FileInfoDemo1 {
public static void main(String[] args) {
File file = new File("Hello.txt");
if (file.exists()) {
System.out.println("File name : " + file.getName());

System.out.println("Absolute path : " + file.getAbsolutePath());

System.out.println("File length : " + file.length());

if (file.canRead()) {
System.out.println("File is readable");

TILOTTAM ZOPE 24
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
} else {
System.out.println("File is not readable");
}

if (file.canWrite()) {
System.out.println("File is writable");
} else {
System.out.println("File is not writable");
}

if (file.canExecute()) {
System.out.println("File is executable");
} else {
System.out.println("File is not executable");
}
} else {
System.out.println("File does not exist.");
}
}
}

➢ Read and Write Operations On File :-


1. For performing read and write operation on file it depends on the types of data the
file will handle the data in file
2. It can be divided into 2 categories i.e.,
a. character stream
b. byte stream
3. character stream and byte stream is used to performing read and write operation
on a file.
4. performing read operation on character stream with the help of file reader class and
we can use the scanner class also for the write operation on character stream with
the help of file writer class
5. For the read operation on byte stream with the help of file input stream class
6. For the write operation on byte stream with the help of file output stream class

TILOTTAM ZOPE 25
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
Data in file

CharaterStream ByteStream

Read Write Read Write


FileReader FileWriter File i/p File o/p
Scanner Scanner Stream Stream

• CharStreamWrite.java :-
package com.jspiders.filehandling.write;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CharStreamWrite {
public static void main(String[] args) {
File file = new File("CharStream.txt");
if (file.exists()) {
System.out.println("File already exists");
} else {
try {
file.createNewFile();
System.out.println("File created");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("Data from program");
System.out.println("Data written to file.");
fileWriter.close();
} catch (IOException e) {
System.out.println("File not created");
e.printStackTrace();
}
}

TILOTTAM ZOPE 26
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
}

• ByteStreamWrite.java :-
package com.jspiders.filehandling.write;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteStreamWrite {
public static void main(String[] args) {
File file = new File("ByteStream.txt");
if (file.exists()) {
System.out.println("File already exists.");
} else {
try {
file.createNewFile();
System.out.println("File created.");
FileOutputStream fileOutputStream =
new FileOutputStream(file);
fileOutputStream.write(20);
System.out.println("Data written to file");
fileOutputStream.close();
} catch (IOException e) {
System.out.println("File not created");
e.printStackTrace();
}
}
}
}

• CharStreamRead.java :-
package com.jspiders.filehandling.read;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class CharStreamRead {

TILOTTAM ZOPE 27
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
public static void main(String[] args) {
File file = new File("CharStream.txt");
if (file.exists()) {
try {
FileReader fileReader = new FileReader(file);
System.out.println("Reading data from file");
System.out.println
("read() output : " + fileReader.read());
Scanner scanner = new Scanner(file);
System.out.print("Scanner output : ");
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
}
}

• ByteStreamRead.java :-
package com.jspiders.filehandling.read;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ByteStreamRead {
public static void main(String[] args) {
File file = new File("ByteStream.txt");
if (file.exists()) {

TILOTTAM ZOPE 28
J2EE-NOTES
FILE HANDLING
------------------------------------------------------------------------------------------
try {
FileInputStream fileInputStream =
new FileInputStream(file);
System.out.println("Reading data from file");
System.out.println(fileInputStream.read());
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("File does not exist.");
}

TILOTTAM ZOPE 29
J2EE-NOTES
SERIALIzATION
&
DESRIALIzATION
------------------------------------------------------------------------------------------
➢ Serialization :-
1. When an object travels over a network it can’t travel in its original format the java
object has to be converted into a byte stream to unable to it travel over the network
2. The conversion of object to byte stream is known as serialization whereas the
conversion of byte stream to object is known as deserialization

Application ByteStream Application

Serialization
java byte
object stream
Desiralization

3. Serialization is the achieve with the help of method writeObject() present in


‘ObjectOutputStream’ class
4. Serialization is the achieve with the help of readObject() present in
‘ObjectInputStream’ class

NOTE :-
• To unable of class for process of serialization and deserialization we need
to implement serializable interface

➢ Serializable :-
1. In java, serializable is a marker interface i.e. used to mark a class for the process of
serialization and deserialization

❖ Marker interface :-
1. In java, marker interfaces are the interfaces that contain no data members and no
methods

TILOTTAM ZOPE 30
J2EE-NOTES
SERIALIzATION
&
DESRIALIzATION
------------------------------------------------------------------------------------------
2. The purpose of the interfaces is to mark a class for a specific purpose and provide
the class for some special ability
3. There are 3 marker interfaces in Java
a. serializable
b. cloneable
c. remote

❖ MethodRight() :-
1. It is a nonstatic method present in ObjectOutputStream class It accepts an object as
argument which is used to serialization purpose

❖ ReadObject() :-
1. It is a non static method present in ObjectInputStream class It returns the object of
supermost class ‘Object’
2. It does not accept any argument which is used for deserialization purpose

• User.java :-
package com.jspiders.serializationdesrialization.object;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
String email;
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name
+ ", email=" + email + "]";
}

TILOTTAM ZOPE 31
J2EE-NOTES
SERIALIzATION
&
DESRIALIzATION
------------------------------------------------------------------------------------------
}

• UserMain.java :-
package com.jspiders.serializationdesrialization.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.jspiders.serializationdesrialization.object.User;
public class UserMain {
public static void main(String[] args) {
try {
File file;
FileInputStream fileInputStream;
FileOutputStream fileOutputStream;
file = new File("Object.txt");
if (file.exists()) {
System.out.println("File already exists");
} else {
file.createNewFile();
System.out.println("File created");
}
fileOutputStream = new FileOutputStream(file);
fileInputStream = new FileInputStream(file);
//Serialization
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(fileOutputStream);
User user = new User(1, "Arjun", "[email protected]");
objectOutputStream.writeObject(user);
System.out.println("Object written to file.");
objectOutputStream.close();

TILOTTAM ZOPE 32
J2EE-NOTES
SERIALIzATION
&
DESRIALIzATION
------------------------------------------------------------------------------------------
//Desrialization
ObjectInputStream objectInputStream =
new ObjectInputStream(fileInputStream);
User output = (User)objectInputStream.readObject();
System.out.println(output);
objectInputStream.close();

} catch (IOException | ClassNotFoundException e) {


e.printStackTrace();
}
}
}

TILOTTAM ZOPE 33
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
1. Design patterns are predefined way or structure of development that can be used in
order to avoid the recurring development issue
2. Design patterns can’t be used in Solve the already occurred issues in the
application depending upon the issues that design patterns this way it can be
categorise into several types, some of the widely used in design patterns are as
follows,
a. Creational design patterns
b. Structural design patterns
c. Behavioral design patterns

a. Creational design patterns :-


The design patterns associated with the issues related to object creations are
categorised as creational design pattern the most widely used creational design
patterns are as follows,
A. Singleton design pattern
B. Factory design pattern
C. Builder design pattern

A. Singleton design pattern :-


1. When a class has to be restricted from multiple objects creation we need to make a
class as Singleton class to do this, We need to restrict the uses of constructor of this
class by external classes it can be achieved by making the constructor private
hence, We need helper method to access the private constructor
2. The initialization of Singleton class object can be done in 2 ways,
i. Lazy instantiation
ii. Eager instantiation

i. Lazy instantiation :-
1. In this case, the object of the class is created only when the user demands for the
object for these, We need to keep an object reference variable of the class already
created but not initialised

ii. eager Instantiation


1. In this case, The object of the class is created, initialise and kept read as soon as the
initialise the instance it automatically create at the same time
2. Whatever the users demands for the object of the class the same reference variable
is written in each type

TILOTTAM ZOPE 34
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
NOTE :-
• In the both ways we need an object reference variable of the class as a static
member

• SingletonLazy.java :-
package com.jspiders.singleton.object;
public class SingletonLazy {
static SingletonLazy object;
private SingletonLazy() {
System.out.println("Constructor accessed.");
}
public static SingletonLazy getObject() {
System.out.println("Method accessed.");
if (object == null) {
object = new SingletonLazy();
}
return object;
}

}
• SingletonLazyMain.java :-
package com.jspiders.singleton.main;
import com.jspiders.singleton.object.SingletonLazy;
public class SingletonLazyMain {
public static void main(String[] args) {
SingletonLazy object1 = SingletonLazy.getObject();
SingletonLazy object2 = SingletonLazy.getObject();
SingletonLazy object3 = SingletonLazy.getObject();
System.out.println(object1);
System.out.println(object2);
System.out.println(object3);
}
}

TILOTTAM ZOPE 35
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
• SingletonEgger.java :-
package com.jspiders.singleton.object;
public class SingletonEager {
static SingletonEager object = new SingletonEager();
private SingletonEager() {
System.out.println("Constructor accessed.");
}
public static SingletonEager getObject() {
System.out.println("Method accessed.");
return object;
}
}

• SingletonEggerMain.java :-
package com.jspiders.singleton.main;
import com.jspiders.singleton.object.SingletonEager;
public class SingletonEagerMain {
public static void main(String[] args) {
SingletonEager object1 = SingletonEager.getObject();
SingletonEager object2 = SingletonEager.getObject();
SingletonEager object3 = SingletonEager.getObject();
System.out.println(object1);
System.out.println(object2);
System.out.println(object3);
}
}

B. Factory design pattern :-


1. The factory design pattern is used to create the objects only when requested.
2. If an application contains several classes for which the object creation is required
and if the objects are created without being requested then there is a chance that the
created object might not be acces at all.
3. This might leed 2 wastage of memory the factory design patterns helps us to avoid
such scenario by creating the object only when it is requested
4. We can say that, The factory design patterns helps us to create the objects of
dynamically run time
5. We want to hide the object creation logic

TILOTTAM ZOPE 36
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
• Bevarage.java :-
baverage
package com.jspiders.factorypattern.beverage;
public interface Beverage {
void order();
}

• Tea.java :-
package com.jspiders.factorypattern.object;
import com.jspiders.factorypattern.beverage.Beverage;
public class Tea implements Beverage {
@Override
public void order() {
System.out.println("Ordered Tea");
}
}

• BlackTea.java :-
package com.jspiders.factorypattern.object;
import com.jspiders.factorypattern.beverage.Beverage;
public class BlackTea implements Beverage {
@Override
public void order() {
System.out.println("Ordered Black Tea.");
}
}

• GingerTea.java :-
package com.jspiders.factorypattern.object;
import com.jspiders.factorypattern.beverage.Beverage;
public class GingerTea implements Beverage {
@Override
public void order() {
System.out.println("Ordered Ginger Tea.");
}
}

TILOTTAM ZOPE 37
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
• MasalaTea.java :-
package com.jspiders.factorypattern.object;
import com.jspiders.factorypattern.beverage.Beverage;
public class MasalaTea implements Beverage {
@Override
public void order() {
System.out.println("Ordered Masala Tea.");
}
}

• TeaFactory.java :-
package com.jspiders.factorypattern.main;
import java.util.Scanner;
import com.jspiders.factorypattern.beverage.Beverage;
import com.jspiders.factorypattern.object.BlackTea;
import com.jspiders.factorypattern.object.GingerTea;
import com.jspiders.factorypattern.object.MasalaTea;
import com.jspiders.factorypattern.object.Tea;
public class TeaFactory {
static Beverage beverage;
public static void main(String[] args) {
try {
factory().order();
} catch (NullPointerException e) {
System.out.println("No tea selected.");
}
}
private static Beverage factory() {
System.out.println("Select Tea to order");
System.out.println("1. Tea\n"
+ "2. Black Tea\n"
+ "3. Ginger Tea\n"
+ "4. Masala Tea");

Scanner scanner = new Scanner(System.in);


int choice = scanner.nextInt();
scanner.close();
switch (choice) {
case 1:
beverage = new Tea();

TILOTTAM ZOPE 38
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
return beverage;

case 2:
beverage = new BlackTea();
return beverage;

case 3:
beverage = new GingerTea();
return beverage;

case 4:
beverage = new MasalaTea();
return beverage;

default:
System.out.println("Invalid choice.");
return beverage;
}

}
}

• Mobile.java :-
package com.jspiders.factorymobile.mobile;
public interface Mobile {
void order();
}

• SamsungS23.java :-
package com.jspiders.factorymobile.object;
import com.jspiders.factorymobile.mobile.Mobile;
public class SamsungS23 implements Mobile {
@Override
public void order() {
System.out.println("Ordered Samsung S23.");
}
}

TILOTTAM ZOPE 39
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
• Pixel7Pro.java :-
package com.jspiders.factorymobile.object;
import com.jspiders.factorymobile.mobile.Mobile;
public class Pixel7Pro implements Mobile {
@Override
public void order() {
System.out.println("Ordered Pixel 7 Pro.");
}
}

• OnePlusPro.java :-
package com.jspiders.factorymobile.object;
import com.jspiders.factorymobile.mobile.Mobile;
public class OnePlus11Pro implements Mobile {
@Override
public void order() {
System.out.println("Ordered OnePlus 11 Pro.");
}
}

• Nothing.java :-
package com.jspiders.factorymobile.object;
import com.jspiders.factorymobile.mobile.Mobile;
public class Nothing1 implements Mobile {
@Override
public void order() {
System.out.println("Ordered Nothing1.");
}
}

• MobileFactory.java :-
package com.jspiders.factorymobile.main;
import java.util.Scanner;
import com.jspiders.factorymobile.mobile.Mobile;
import com.jspiders.factorymobile.object.Nothing1;
import com.jspiders.factorymobile.object.OnePlus11Pro;
import com.jspiders.factorymobile.object.Pixel7Pro;
import com.jspiders.factorymobile.object.SamsungS23;
public class MobileFactory {
static Mobile mobile;

TILOTTAM ZOPE 40
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
public static void main(String[] args) {
try {
factory().order();
} catch (NullPointerException e) {
System.out.println("No mobile selected.");
}
}
private static Mobile factory() {
System.out.println("Select Mobile To Order");
System.out.println("1. Samsung S23\n" + "2. Pixel 7 Pro\n" + "3. OnePlus 11
Pro\n" + "
4. Nothing1");

Scanner scanner = new Scanner(System.in);


int choice = scanner.nextInt();
scanner.close();

switch (choice) {
case 1:
mobile = new SamsungS23();
return mobile;

case 2:
mobile = new Pixel7Pro();
return mobile;

case 3:
mobile = new OnePlus11Pro();
return mobile;

case 4:
mobile = new Nothing1();
return mobile;

default:
System.out.println("Invalid choice.");
return mobile;
}
}
}

TILOTTAM ZOPE 41
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
C. Builder design pattern :-
1. The builder design pattern is used to initialise complex objects
2. If an object has too many properties that are mandatory to be initialised in an
excepted sequence then search object can we considered as a complex object
3. Create the complex object we need to take help of the builder class which is
responsible to access the constructor and initialise the properties of the complex
object
4. The builder class is aware of the properties of the class properties whose object has
to be created

• Contact.java :-
package com.jspiders.builderdesignpattern.object;
public class Contact {
String first_name;
String middle_name;
String last_name;
String nickname;
String email;
long mobile_no;
long landline_no;
String dob;
String company;
String address;
String gender;
public Contact(String first_name, String middle_name,
String last_name, String nickname, String email,
long mobile_no, long landline_no, String dob,
String company, String address, String gender) {

this.first_name = first_name;
this.middle_name = middle_name;
this.last_name = last_name;
this.nickname = nickname;
this.email = email;
this.mobile_no = mobile_no;
this.landline_no = landline_no;
this.dob = dob;
this.company = company;
this.address = address;

TILOTTAM ZOPE 42
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
this.gender = gender;
}
@Override
public String toString() {
return "Contact :"
+ "\nfirst_name :" + first_name
+ "\nmiddle_name :" + middle_name
+ "\nlast_name :" + last_name
+ "\nnickname :" + nickname
+ "\nemail :" + email
+ "\nmobile_no :" + mobile_no
+ "\nlandline_no :" + landline_no
+ "\ndob :" + dob
+ "\ncompany :" + company
+ "\naddress :" + address
+ "\ngender :" + gender;
}
}

• ContactBulitder.java :-
package com.jspiders.builderdesignpattern.builder;
import com.jspiders.builderdesignpattern.object.Contact;
public class ContactBuilder {
private String first_name;
private String middle_name;
private String last_name;
private String nickname;
private String email;
private long mobile_no;
private long landline_no;
private String dob;
private String company;
private String address;
private String gender;
public ContactBuilder first_name(String first_name) {
this.first_name = first_name;
return this;
}

public ContactBuilder middle_name(String middle_name) {

TILOTTAM ZOPE 43
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
this.middle_name = middle_name;
return this;
}

public ContactBuilder last_name(String last_name) {


this.last_name = last_name;
return this;
}

public ContactBuilder nickname(String nickname) {


this.nickname = nickname;
return this;
}

public ContactBuilder email(String email) {


this.email = email;
return this;
}

public ContactBuilder mobile_no(long mobile_no) {


this.mobile_no = mobile_no;
return this;
}

public ContactBuilder landline_no(long landline_no) {


this.landline_no = landline_no;
return this;
}

public ContactBuilder dob(String dob) {


this.dob = dob;
return this;
}

public ContactBuilder company(String company) {


this.company = company;
return this;
}

public ContactBuilder address(String address) {


this.address = address;

TILOTTAM ZOPE 44
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
return this;
}

public ContactBuilder gender(String gender) {


this.gender = gender;
return this;
}

public Contact getContact() {


Contact contact = new Contact(this.first_name, this.middle_name,
this.last_name, this.nickname, this.email,
this.mobile_no, this.landline_no, this.dob,
this.company, this.address, this.gender);
return contact;
}
}

• ContactMain.java :-
package com.jspiders.builderdesignpattern.main;
import com.jspiders.builderdesignpattern.builder.ContactBuilder;
import com.jspiders.builderdesignpattern.object.Contact;
public class ContactMain {
public static void main(String[] args) {
Contact contact = new ContactBuilder()
.mobile_no(9876543210L)
.last_name("Sharma")
.first_name("Rohit").getContact();
System.out.println(contact);
}
}

b. Structural design pattern :-


1. It provides a manner to define the relationship between classes and object.

A. adapter design pattern :-


adapter design pattern is used to adapt the properties of one entity and the
behaviour of another entity without having to establish any direct relationship
between the two entity

TILOTTAM ZOPE 45
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
e1 e2

class interface
property method

extends implements
Adapter
class

• Employee.java :-
package com.jspiders.adapterpatttern.object;
public class Employee {
private int emp_id;
private String name;
public int getEmp_id() {
return emp_id;
}

public void setEmp_id(int emp_id) {


this.emp_id = emp_id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

TILOTTAM ZOPE 46
J2EE-NOTES
DESIGN pATTERN
------------------------------------------------------------------------------------------
• Event.java :-
package com.jspiders.adapterpatttern.interfaces;
public interface Events {
void mothersDay();
void fathersDay();
}

• EmpEventAdapter.java :-
package com.jspiders.adapterpatttern.adapter;
import com.jspiders.adapterpatttern.interfaces.Events;
import com.jspiders.adapterpatttern.object.Employee;
public class EmpEventsAdapter extends Employee implements Events {
@Override
public void mothersDay() {
EmpEventsAdapter employee1 = new EmpEventsAdapter();
employee1.setEmp_id(1);
employee1.setName("Aishwarya");
System.out.println("Chief guest of the event is "
+ employee1.getName());
}
@Override
public void fathersDay() {
EmpEventsAdapter employee2 = new EmpEventsAdapter();
employee2.setEmp_id(2);
employee2.setName("Salman");
System.out.println("Chief guest of the event is "
+ employee2.getName());
}
public static void main(String[] args) {
EmpEventsAdapter adapter = new EmpEventsAdapter();
adapter.mothersDay();
adapter.fathersDay();
}
}

c. Behavioral design pattern


1. It defines the manner of communication between classes and objects

TILOTTAM ZOPE 47
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
1. JDBC stands for Java database connectivity which is used for connect java
application to a database application in order to same the data from the application
inside the database / java code application
1. The data need to store outside the application for future uses.
2. The JDBC can also be considered as an API as it helps to establish communication
between two different applications
3. As the Java application unders only the Java programming language whereas the
database application can understand only the query language hence both these
applications are incapable of connecting with each other directly
4. Here, JDBC acts as a mediator JDBC unders stands the Java programming
language as well as the query language
5. It translates the Java code from the Java application to the query language & sends
it to the database it takes output from the database in the form of query language &
converts it to the Java programming language before sending it to the Java
application

➢ API (application programming interface) :-


1. The technology that helps us to establish communication between two different
application can be called as an API

java J query
Java D Qurey
Code B Language
java C query

Java DB
Appn

Driver
JDBC

Java DB
Appn

TILOTTAM ZOPE 48
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
2. As the JDBC logic is a part of the Java application it cannot directly perform
operations on the database Hence, the JDBC appoins a driver class to create a
bridge between JDBC and the database
3. The driver class is not responsible to perform any logical operation instead it is
only responsible to transfer the data from JDBC to database and vice versa

➢ Steps of JDBC :-
1. There are five steps involved in a JDBC logic
a. load the driver class
b. open connections
c. create or prepare prepare statement
d. process the result
e. close connections

➢ Prerequisites for JDBC project :-


1. make java Version for project as ‘1.8’ for this we need to perform below steps ;
a. Right click on the project go the ‘build Path’ then select ‘configured build path’
in the build path window go to the ‘library’ section double click on the ‘JRE
system library’ options change the Java version to 1.8 and then click on apply.
b. Go to the ‘project facets’ and the change the Java version to 1.8 and then click
on apply and close

2. We need to add the ‘Mysql connector’ jar file to the project build path for this we
need to perform the below steps ;
a. Go to the google and search for ‘mevenrepository’.
b. In the repository, search for ‘Mysql connector’
c. Select the version for the file same as the ‘Mysql server’ version
d. Select the jar file for that version and to download it
e. Right click on the ‘project’ and then go to the ‘build path’ and then select
‘configured build path’
f. Inside the ‘build path’ window go to the ‘library section’ and then click on
‘Add external jar’ button
g. Locate the file in the system and open it and then click on apply and close
h. To verify the process check the ‘reference library’ section and see if the added
jar file exits or not

TILOTTAM ZOPE 49
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
➢ Establishing connection :-
1. In JDBC, there are 3 ways of establishing connection with the database
2. The 3 ways are satisfied by a method ‘getConnection’ which is an overloaded
method
a. getConnection (String dburl)
b. getConnection (string url, String user, String password)
c. getConnection (String url, Properties property)

❖ 1st way of connection :-


• dburl :-
a. The dburl is a string value i.e. required to locate the database i.e. under operation.
b. The format of dburl a JDBC is as a below,

protocol : sub-protocol://host:port_no/db_name?
user = “username” & passowrd = “password”

protocol :-
In JDBC, the protocol is mentioned as ‘jdbc’

sub-protocol :-
The sub-protocol is the database technology for which the JDBC is used for
example ‘Mysql’

host :-
i. The host name represent the system where the database application is installed
ii. If the JDBC program and the database application are present in the same system
then the host name is given as ‘localhost’ or else it is given as IP address of the m/c
where the database application is present

port_no :-
The port_no is used to identify the exact address of the database application on the
system identified through the host_name

db_name ? :-
The db_name represent the database i.e. currently under operation

TILOTTAM ZOPE 50
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
user :-
The user indicates the name of the account in which the database is present

password :-
It is used to provide a password of identified user account

➢ example of a db url :-
jdbc = mysql://localhost:3306/weja1?
user = root & password = root

NOTE :-
➢ The database need based in the url must exists.

• JdbcSelectDemo.java :-
package com.jspiders.jdbc.select;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSelectDemo {
public static void main(String[] args) {

try {
//1. Load the driver class
Class.forName("com.mysql.cj.jdbc.Driver");

//2. Open Connections


Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/weja1?"
+ "user=root&password=root");

//3. Create statement


Statement statement = connection.createStatement();
ResultSet resultSet =
statement.executeQuery("select * from student");

//4. Process the result


while (resultSet.next()) {

TILOTTAM ZOPE 51
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
System.out.println(resultSet.getInt(1) + " || "
+ resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getLong(4));
}

//5. Close connections


connection.close();
statement.close();
resultSet.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

❖ 2nd way of connection :-


• JdbcSelectDemo2.java :-
package com.jspiders.jdbc.select;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSelectDemo2 {
public static void main(String[] args) {

try {
//1. Load the driver class
Class.forName("com.mysql.cj.jdbc.Driver");

//2. Open Connections


Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/weja1","root","root");

//3. Create statement


Statement statement = connection.createStatement();
ResultSet resultSet =

TILOTTAM ZOPE 52
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
statement.executeQuery("select * from student");
//4. Process the result
while (resultSet.next()) {
System.out.println(resultSet.getInt(1) + " || "
+ resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getLong(5));
}

//5. Close connections


connection.close();
statement.close();
resultSet.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

• JdbcSelectDemo3.java :-
package com.jspiders.jdbc.select;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcSelectDemo3 {
private static Connection connection;
private static Statement statement;
private static ResultSet resultSet;
private static String driverPath = "com.mysql.cj.jdbc.Driver";
private static String dburl = "jdbc:mysql://localhost:3306/weja1";
private static String user = "root";
private static String password = "root";
private static String query;
public static void main(String[] args) {
try {
Class.forName(driverPath);

TILOTTAM ZOPE 53
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
connection = DriverManager.getConnection(dburl, user, password);
statement = connection.createStatement();
query = "select * from student";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " || "
+ resultSet.getString(2));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

TILOTTAM ZOPE 54
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
❖ 3rd way of connection :-
1. In the previous two ways of establishing the connection in JDBC, the database
credential (username and password) are exposed in the program itself hence there
will be a chance of illegal access to the database which can lead to data leakage
2. In order to squence the database credential we must avoid declaring the credential
in the program the program itself
3. As the credentials are the properties of my database hence, it has to be stored in a
properties file
4. In order to do so we need to establish the connection with the help of ‘properties’
class object

➢ Creating the property file :-


1. The properties file as to be created in a specific location
2. We need to create a general folder under the project with the name ‘Resources’
3. Under the resources folder we need to create a general file with the name
‘db_info.properties’
4. The database credential in the properties file have to be defined in the form of
key-value pair

❖ db_info.properties :-
user = root
password = root

• JdbcSelectDemo4.java :-
package com.jspiders.jdbc.select;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcSelectDemo4 {
private static Connection connection;
private static Statement statement;

TILOTTAM ZOPE 55
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
private static ResultSet resultSet;
private static FileReader fileReader;
private static Properties properties;
private static String driverPath = "com.mysql.cj.jdbc.Driver";
private static String dburl = "jdbc:mysql://localhost:3306/weja1";
private static String filePath =
"D:\\WEJA1\\jdbc\\resources\\db_info.properties";
private static String query;
public static void main(String[] args) {

try {
Class.forName(driverPath);
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
connection = DriverManager.getConnection(dburl, properties);
statement = connection.createStatement();
query = "select * from student";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " || "
+ resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getString(4));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();

TILOTTAM ZOPE 56
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
}
if (resultSet != null) {
resultSet.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

❖ db_info.property :-
user = root
password = root
driverPath = com.mysql.cj.jdbc.Driver
dburl = jdbc:mysql://localhost:3306/weja1
query = select * from student

• JdbcSelectDemo5.java :-
package com.jspiders.jdbc.select;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcSelectDemo5 {
private static Connection connection;
private static Statement statement;
private static ResultSet resultSet;
private static FileReader fileReader;
private static Properties properties;

TILOTTAM ZOPE 57
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
private static String filePath =
"D:\\WEJA1\\jdbc\\resources\\db_info.properties";
public static void main(String[] args) {
try {

fileReader = new FileReader(filePath);


properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
statement = connection.createStatement();
resultSet = statement.executeQuery
(properties.getProperty("query"));
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getString(4));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (fileReader != null) {
fileReader.close();

TILOTTAM ZOPE 58
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

❖ Jdbc CRUD Operation :-


➢ Insert Operation :-
• JdbcInsertDemo1.java :-
package com.jspiders.jdbc.insert;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcInsertDemo1 {
private static Connection connection;
private static Statement statement;
private static int result;
private static FileReader fileReader;
private static Properties properties;
private static String filePath =
"D:\\WEJA1\\jdbc\\resources\\db_info.properties";
private static String query;
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
statement = connection.createStatement();

TILOTTAM ZOPE 59
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
query = "insert into student values"
+ "(4, 'Jethalal', '[email protected]', 7658943201)";
result = statement.executeUpdate(query);
System.out.println
("Query OK, " + result + " row(s) affected.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

➢ Update Operation :-
• JdbcUpdateDemo1.java :-
package com.jspiders.jdbc.update;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;

TILOTTAM ZOPE 60
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUpdateDemo1 {
private static Connection connection;
private static Statement statement;
private static int result;
private static FileReader fileReader;
private static Properties properties;
private static String filePath =
"D:\\WEJA1\\jdbc\\resources\\db_info.properties";
private static String query;
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
statement = connection.createStatement();
query = "update student "
+ "set email = '[email protected]' "
+ "where id = 4";
result = statement.executeUpdate(query);
System.out.println
("Query OK, " + result + " row(s) affected.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}

TILOTTAM ZOPE 61
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
if (statement != null) {
statement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

➢ Delete Operation :-
• JdbcDeleteDemo1.java :-
package com.jspiders.jdbc.delete;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcDeleteDemo1 {
private static Connection connection;
private static Statement statement;
private static int result;
private static FileReader fileReader;
private static Properties properties;
private static String filePath =
"D:\\WEJA1\\jdbc\\resources\\db_info.properties";
private static String query;
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);

TILOTTAM ZOPE 62
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
statement = connection.createStatement();
query = "delete from student "
+ "where id = 4";
result = statement.executeUpdate(query);
System.out.println
("Query OK, " + result + " row(s) affected.");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

TILOTTAM ZOPE 63
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
➢ difference between ExecuteQuery and ExecuteUpdate :-

No. ExecuteQuery ExecuteUpdate


This method is used to
This method is used to
1. Execute insert, update,
execute ‘select’ query
delete operation etc
This method is used to retrive some This method is used to
2. data from the database without update or change the data in
affecting it the database
The return type of this The return type of
3. method is the object of this method is int
‘ResultSet’ interface
❖ Connection interface :-
a. The object of this interface is obtain with the help of ‘getConnection()’ from the
drivermanager class
b. It is required to obtain the object of ‘statement interface’

❖ Statement interface :-
a. The object of this interface is obtained with the help of createStatement() from the
connection interface
b. It is used to obtain the object of ‘ResultSet interface’ or an integer value as the
output of the query

❖ ResultSet interface :-
a. The object of interface is obtained with the help of execute query method from the
statement interface
b. It is required to obtain the output of the select query

TILOTTAM ZOPE 64
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
➢ Dynamic query :-
1. It is used to compile a query and keep it ready for execution without actual values
in it Although
2. It’s for the values in the query have to be reserved
3. It can be reserved with the help of a symbol called as placeholder i.e. represented
by ‘ ? ’.
4. The number of placeholders in the query will represent the number of values
required for the query to be executed
5. The statement interface is not capable of handling dynamic queries in order to
handle the dynamic query we need to use the ‘PreparedStatement’ interface
6. With the help of interface we can compile the query before its execution and
provide the values whenever the query has to be executed
7. The ‘PreparedStatement’ interface is capable of handling dynamic as well as static
queries. It is possible because the PreparedStatement interface internally extends
the statement interface

jdbc dynamic resources :-


user = root
password = root
dburl = jdbc:mysql://localhost:3306/weja1
driverPath = com.mysql.cj.jdbc.Driver

❖ Jdbc Dynamic CRUD operation :-


➢ Insert operation :-
• DynamicInsert.java :-
package com.jspiders.jdbcdynamic.insert;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class DynamicInsert {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static FileReader fileReader;
private static Properties properties;

TILOTTAM ZOPE 65
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
private static int result;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcdynamic\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "insert into "
+ "student values "
+ "(?,?,?,?)";
preparedStatement = connection.prepareStatement(query)
preparedStatement.setInt(1, 4);
preparedStatement.setString(2, "Babita");
preparedStatement.setString(3, "[email protected]");
preparedStatement.setLong(4, 9876542310L);
result = preparedStatement.executeUpdate();
System.out.println
("Query OK, " + result + " row(s) affected.");
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}

TILOTTAM ZOPE 66
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
}

• The binding of the query of the value happens at runtime Hence, it is known as
dynamic query.

➢ Select Operation :-
• DynamicSelect.java :-
package com.jspiders.jdbcdynamic.select;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DynamicSelect {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static ResultSet resultSet;
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcdynamic\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "select * "
+ "from student "
+ "where id = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, 2);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {

TILOTTAM ZOPE 67
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
System.out.println(resultSet.getInt(1) + " || "
+ resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getLong(4));
}
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
}

➢ Update Operation :-
• DynamicUpdate.java :-
package com.jspiders.jdbcdynamic.update;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
public class DynamicUpdate {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static int result;

TILOTTAM ZOPE 68
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcdynamic\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "update student "
+ "set email = ? "
+ "where id = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "[email protected]");
preparedStatement.setInt(2, 5);
result = preparedStatement.executeUpdate();
System.out.println
("Query OK, " + result + " row(s) affected.");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

TILOTTAM ZOPE 69
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
➢ Delete operation :-
• DynamicDelete.java :-
package com.jspiders.jdbcdynamic.delete;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
public class DynamicDelete {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static int result;
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcdynamic\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "delete from student "
+ "where id = ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, 5);
result = preparedStatement.executeUpdate();
System.out.println
("Query OK, " + result + " row(s) affected.");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {

TILOTTAM ZOPE 70
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
preparedStatement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

❖ Stored procedure :-
1. Like methods in Java, We can we can create procedure in SQL the procedure can
be declared and called for the execution whenever required
2. The stored procedure helps us to execute more than one query in single statement
It also helps us to execute the same query multiple times

➢ Syntax for Declaration :-


delimeter /
create procedure proc_name()
begin
statement 1
statement 2
statement 3
:
:
:
statement nth
end /
delimeter ;

➢ Example ;
delimeter /
create procedure proc1()
begin
select * from student ;

TILOTTAM ZOPE 71
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
end /
Query ok, 0 rows affected(0.03 sec)
delimeter ;

NOTE :-
• To execute a stored procedure calling from ‘JDBC program’ We need to make use
of a statement called as ‘collable statement’
• The object of this interface can be obtained from a method ‘preparedCall()’ which
is represent in the connection interface

• CollableDemo.java :-
package com.jspiders.jdbcdynamic.callable;
import java.io.FileReader;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class CallableDemo {
private static Connection connection;
private static CallableStatement callableStatement;
private static ResultSet resultSet;
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcdynamic\\resources\\db_info.properties";
public static void main(String[] args) {
try {

fileReader = new FileReader(filePath);


properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "call proc1()";

TILOTTAM ZOPE 72
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
callableStatement = connection.prepareCall(query);
resultSet = callableStatement.executeQuery();
while (resultSet.next()) {
System.out.println(resultSet.getInt(1) + " || "
+ resultSet.getString(2) + " || "
+ resultSet.getString(3) + " || "
+ resultSet.getLong(4));
}
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (callableStatement != null) {
callableStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
}

• The main motive of JDBC program is to take the objects from the Java application
and stored it in the database this can be done in JDBC by replacing the raw data
values in the query by object data values in the order to do this We need to create
an entity class whose object will be saved in the database

TILOTTAM ZOPE 73
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
❖ db_infoproperties :-
user = root
password = root
dburl = jdbc:mysql://localhost:3306/weja1
driverPath = com.mysql.cj.jdbc.Driver

• Student.java :-
package com.jspider.jdbcobject.entity;
public class Student {
private int id;
private String name;
private String email;
private long contact;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getContact() {
return contact;
}
public void setContact(long contact) {
this.contact = contact;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name

TILOTTAM ZOPE 74
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
+ ", email=" + email + ", contact=" + contact + "]";
}
}

• StudentSelect.java :-
package com.jspider.jdbcobject.select;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import com.jspider.jdbcobject.entity.Student;
public class StudentSelect {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static ResultSet resultSet;
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcobject\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);

Class.forName(properties.getProperty("driverPath"));

connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);

query = "select * "


+ "from student ";
preparedStatement = connection.prepareStatement(query);

resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setEmail(resultSet.getString(3));

TILOTTAM ZOPE 75
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
student.setContact(resultSet.getLong(4));
System.out.println(student);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

TILOTTAM ZOPE 76
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
• StudentInsert.java :-
package com.jspider.jdbcobject.insert;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
import com.jspider.jdbcobject.entity.Student;
public class StudentInsert {
private static Connection connection;
private static PreparedStatement preparedStatement;
private static int result;
private static FileReader fileReader;
private static Properties properties;
private static String query;
private static String filePath =
"D:\\WEJA1\\jdbcobject\\resources\\db_info.properties";
public static void main(String[] args) {
try {
fileReader = new FileReader(filePath);
properties = new Properties();
properties.load(fileReader);
Class.forName(properties.getProperty("driverPath"));
connection = DriverManager.getConnection
(properties.getProperty("dburl"), properties);
query = "insert into student "
+ "values (?,?,?,?)";
preparedStatement = connection.prepareStatement(query);
Student student = new Student();
student.setId(5);
student.setName("Jethalal");
student.setEmail("[email protected]");
student.setContact(9576842310L);
preparedStatement.setInt(1, student.getId());
preparedStatement.setString(2, student.getName());
preparedStatement.setString(3, student.getEmail());
preparedStatement.setLong(4, student.getContact());
result = preparedStatement.executeUpdate();
System.out.println
("Query OK, " + result + " row(s) affected");

TILOTTAM ZOPE 77
J2EE-NOTES
JDbc
------------------------------------------------------------------------------------------
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (fileReader != null) {
fileReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

TILOTTAM ZOPE 78
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
➢ ORM :-
1. ORM stands for Object Relational Mapping which is used to map java objects to
the relational database
2. ORM is built over the jdbc framework itself it was developed to overcome the
drawbacks object JDBC

➢ Drawbacks of jdbc :-
1. As a Java developers, we are force to known as SQL concept in order to implement
the developer need to take care of the database properties as well
2. As a Java developer we are force to write SQL queries
3. There is no direct relationship between the Java objects and the data inside the
database

➢ Features of ORM :-
1. With the help of orm we can avoid writing jdbc logic
2. We don’t need to take care of the database a properties for every new operation
3. The database properties can be initialised once and multiple times
4. With the help of orm, we don’t need to write queries for database operation
5. The orm tools write the query on its own
6. In the ORM, the objects are directly mapped to data inside the database

NOTE :-
• Orm is technologies which is implemented by various tools one of the most
orm tools is hibernate
• Hibernate is most popular because it is rich in feature and open source

➢ HIBERNATE JPA :-
1. Initially the tool was developed as hibernate core and just like that many other orm
tools were also developed
2. All these orm tools were incapable table to understand the logics implemented by
other orm tools
3. Hence, it was highly inconvenient to migrate from one orm tool to another
4. Here, JPA was introduced (JPA stands for Java Versistance API) it means the ORM
tools implemented for Java applications now had common standards
5. This is when hibernate JPA was developed.

TILOTTAM ZOPE 79
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
➢ Creating maven project :-
1. Step1 :- Go to the package explorer and press ‘ctrl + N’
2. Step2 :- In the winzard window search for ‘maven’ and select ‘maven project’ and
then click on next
3. Step3 :- In the ‘new maven project’ window click on next
4. Step4 :- In the next window verify that the catalog is set to all catalogs
5. Step5 :- In the filter textbox type : ‘org. Apache. Maven’
6. Step6 :- From the filtered options select the ‘ArcheType’ as ‘maven-archetype
quickstart’ of the version 1.4 then click on next
7. Steps7 :- The next new window enter the group ID in the format of
‘domaim.host_name’ in the artifacts ID enter the ‘project_name’
8. Step8 :- Untick the option of ‘run archetype generation interactly’ & then click on
finish.

➢ Maven Project Structure :-


>hibernate
>src/main/java
>com.jspiders.hibernate
>App.java
>src/test/java
>JRE System Library
>maven dependencies
>src
O target
>pom.xml

➢ Configuring maven project for hibernate implementation :-


1. Changing the Java version to 1.8 :-
a. Change the Java version from the libraries tab in the project build path.
b. Change the Java version from project facets
c. Go to the pom.xml file , the properties tag change the Java version mention
within the name ‘<maven.compiler.source>’ & ‘<maven.compiler.target>’
tags.

TILOTTAM ZOPE 80
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
2. Add the required dependencies in the pom.xml file :-
a. Go to the pom.xml file and search for the <dependencies> tag.
b. Copy and paste the <dependency> tag of the required jar file within the
<dependences> tag
3. Creating the structure for persistence.xml :-
a. Create a new source folder inside the project by the name src/main/resources
b. Inside the source folder create a new general folder by the name ‘META-INF’
c. Inside the ‘META-INF’ folder create a new xml file by the name ‘persistance’

NOTE :-
• hibernate looks for the persistence configuration on its own in specific
location under the project ‘src/main/resources/META-INF/persistance.xml’

➢ Dependencies required for hibernate :-


a. MySql connector
b. Hibernate core (Relocation)
c. Hibernate Entity Manager
d. lombok (optional)

➢ pom :-
1. pom stands for project object model.
2. It is used to provide the configuration for the objects required for the project
development.
3. We can add dependencies to this file for which it will download and add the
relevant jar file.

➢ Configuring persistence.xml :-
1. Go to the maven dependencies section and search for a jar file name as
‘javax.persistence-api-1.2.0’.
2. Inside the jar file open the package named as Javax.persistance and Scroll down
the bottom of the package.
3. Open the file ‘persistence-_2.1.xsd’
4. In the xsd file copy the black coloured text from the line number 50 to56 and
added to the persistence.xml file.
5. Remove the 3 dots present within the <persistence> tag
6. Add the <persistence- unit> tag <provider> tag , <properties> tag and <property>
tag within the <persistence> tag.

TILOTTAM ZOPE 81
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
➢ Hibernate Layers :-

Hibernate Logic Entity

Data-
DAO DTO base

Data-access Data-transfer
object object

1. The DTO layer is responsible to hold the entity classes whose object will be
transferred from Java to database and vice-versa
2. The DAO layer is a responsible to hold the hibernate logic the DTO layer entity
class objects will be access in the DAO layer hence the name data-access object

NOTE :-
• The hibernate layers are represented as the packages in the programm

➢ Adding content persistence.xml :-


1. Create a <persistence-unit> tag and give a suitable name
2. Add the provider tag and mention the qualified name of the provider class
a. press ‘ctrl + shift + T’ and search for ‘HibernatePersistenceProvider’
b. Open the class and right click on the class name
c. Copy the qualified name of the class, go back to the persistence file and paste
it within the provider tag
3. Add the <properties> tag and initialize the required properties within the
<property> tags

➢ Properties in persistence.xml :-
a. Driver Path
b. Database url
c. Database username
d. Database password
e. Hibernate mapping protocol
f. Display query
g. Hibernate dialcet

TILOTTAM ZOPE 82
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
➢ Dialect property :-
1. Step1 :- Go to the maven dependencies section and search for hibernate- core jar
file.
2. Step2 :- In the jar file search for the package ‘org.hibernate.dialect’.
3. Step3 :- In this package search for the ‘MySql8 Dialect class’.
4. Step4 :- Open the class and copy the qualified name of the class.
5. Step5 :- Go to the persistence file and paste the qualified name as the value.

• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="emp">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?
createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

TILOTTAM ZOPE 83
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
NOTE :-
• ‘CreateDatabaseIfNotExist’ can be added to the database url whose default
value is ‘False’ the value for this can be explicit True in order to create the
database dynamically if it does not already exist
• The value for hibernate mapping protocol property can be defined as ‘Update’
or ‘Create’

• EmployeeDTO.java :-
package com.jspiders.hibernate.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class EmployeeDTO {
@Id
private int id;
private String name;
private String email;
private long contact;
}

• EmployeeDAO.java :-
package com.jspiders.hibernate.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernate.dto.EmployeeDTO;
public class EmployeeDAO {
private static EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;
private static EntityTransaction entityTransaction;
private static void openConnection() {
entityManagerFactory =
Persistence.createEntityManagerFactory("emp");
entityManager = entityManagerFactory.createEntityManager();
entityTransaction = entityManager.getTransaction();

TILOTTAM ZOPE 84
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
}
private static void closeConnection() {
if (entityManagerFactory != null) {
entityManagerFactory.close();
}
if (entityManager != null) {
entityManager.close();
}
if (entityTransaction.isActive()) {
entityTransaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();

entityTransaction.begin();

EmployeeDTO employee1 = new EmployeeDTO();


employee1.setId(4);
employee1.setName("Komal");
employee1.setEmail("[email protected]");
employee1.setContact(9875641531L);

entityManager.persist(employee1);

entityTransaction.commit();

} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
}

TILOTTAM ZOPE 85
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
➢ @Data :-
1. It is a class level annotation which is used to obtain the boiler plate code for the
class properties it includes the structures search as getters and setters, to-string(),
equals(), etc.
2. It is present in lombok package

➢ @entity :-
1. It is a class level annotation which is used to specify that the annotated class is the
entity on which hibernate has to operate
2. It is a mandatory annotation

➢ @Id :-
1. It is a property level annotation which is used to specify that the annotated property
will be the primary key column.
2. It is a mandatory annotation.

➢ persists() :-
1. This is a non static method present in the Entity-Manager Interface
2. It is used to say, the object of the entity class as a record in the database table

• EmpUpdateDAO.java :-
package com.jspiders.hibernate.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernate.dto.EmployeeDTO;
public class EmployeeUpdateDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("emp");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {

TILOTTAM ZOPE 86
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();
transaction.begin();
EmployeeDTO employee = manager.find(EmployeeDTO.class, 2);
employee.setEmail("[email protected]");
manager.persist(employee);
transaction.commit();
} finally {
closeConnection();
}
}
}

• EmpDeleteDAO.java :-
package com.jspiders.hibernate.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernate.dto.EmployeeDTO;
public class EmpDeleteDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("emp");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {

TILOTTAM ZOPE 87
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();
transaction.begin();
EmployeeDTO employee = manager.find(EmployeeDTO.class, 1);
manager.remove(employee);
transaction.commit();
} finally {
closeConnection();
}
}
}

• EmpFindDAO.java :-
package com.jspiders.hibernate.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernate.dto.EmployeeDTO;
public class EmpFindDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("emp");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {

TILOTTAM ZOPE 88
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();
transaction.begin();
EmployeeDTO employee = manager.find(EmployeeDTO.class, 1);
System.out.println(employee);
transaction.commit();
} finally {
closeConnection();
}
}
}

➢ Hibernate Mapping :-
1. Hibernate mapping is used to establish and define logical relationship between to
different entities
2. Depending on the nature of relationship the hibernate mapping are classified into 4
types ;
a. one to one
b. one to many
c. many to one
d. many to many
a. one to one :-
T1 T2
R1 R1

R2 R2

R3 R3

TILOTTAM ZOPE 89
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
1. When one record from table one is related to exactly one record from Table 2 then
the relationship between the Table1 and Table 2 is considered to be one to one
2. If the relationship is defined in either one of the tables then the relationship is
considered to be unidirectional relationship.
3. But if the relationship is defined in both the tables and the relationship is
considered to be one to one bidirectional relationship.

• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="aadhar">

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?
createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

TILOTTAM ZOPE 90
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
• AdharDTO.java :-
package com.jspiders.hibernateonetoone.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import lombok.Data;
@Data
@Entity
public class AadharDTO {
@Id
private int id;
private long aadhar_no;
private String date_of_issue;
@OneToOne
private PersonDTO person;
}

• PersionDTO.java :-
package com.jspiders.hibernateonetoone.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import lombok.Data;
@Data
@Entity
public class PersonDTO {
@Id
private int id;
private String name;
private String city;
private long contact;
@OneToOne
private AadharDTO aadhar;

• PersionAdharDAO.java :-
package com.jspiders.hibernateonetoone.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

TILOTTAM ZOPE 91
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernateonetoone.dto.AadharDTO;
import com.jspiders.hibernateonetoone.dto.PersonDTO;
public class PersonAadharDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("aadhar");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {

try {
openConnection();
transaction.begin();
PersonDTO person = new PersonDTO();
person.setId(1);
person.setName("Avinash");
person.setCity("Banglore");
person.setContact(9576841230L);
AadharDTO aadhar = new AadharDTO();
aadhar.setId(1);
aadhar.setAadhar_no(123456789012L);
aadhar.setDate_of_issue("15-Nov-2020");
aadhar.setPerson(person);
person.setAadhar(aadhar);
manager.persist(person);

TILOTTAM ZOPE 92
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
manager.persist(aadhar);
transaction.commit();

} finally {
closeConnection();
}
}
}

b. one to many :-

T1 T2
R1

R1 R2

R2
R3

R4

1. when one record from table one is related to more than one records from Table 2
then the relationship between the 2 tables is considered to be one to many
2. In this type of mapping we establish only unidirectional relationship.
• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="OneToMany">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?
createDatabaseIfNotExist=true" />

TILOTTAM ZOPE 93
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

• EmployeeDTO.java :-
package com.jspiders.hibernateonetomany.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class EmployeeDTO {
@Id
private int id;
private String name;
private String email;
private String designation;
private double salary;

• CompanyDTO.java :-
package com.jspiders.hibernateonetomany.dto;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import lombok.Data;
@Data
@Entity
public class CompanyDTO {
@Id

TILOTTAM ZOPE 94
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
private int id;
private String name;
private String city;
@OneToMany
private List<EmployeeDTO> employees;

• CompEmpDAO.java :-
package com.jspiders.hibernateonetomany.dao;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernateonetomany.dto.CompanyDTO;
import com.jspiders.hibernateonetomany.dto.EmployeeDTO;
public class CompEmpDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("OneToMany");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}

public static void main(String[] args) {

TILOTTAM ZOPE 95
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
try {

openConnection();

transaction.begin();

EmployeeDTO employee1 = new EmployeeDTO();


employee1.setId(1);
employee1.setName("Raju");
employee1.setEmail("[email protected]");
employee1.setDesignation("Schemer");
employee1.setSalary(150);
manager.persist(employee1);

EmployeeDTO employee2 = new EmployeeDTO();


employee2.setId(2);
employee2.setName("Babu Bhaiya");
employee2.setEmail("[email protected]");
employee2.setDesignation("Owner");
employee2.setSalary(150);
manager.persist(employee2);

List<EmployeeDTO> employees =
Arrays.asList(employee1, employee2);

CompanyDTO company1 = new CompanyDTO();


company1.setId(1);
company1.setName("Hera Pheri");
company1.setCity("Dange Chowk");
company1.setEmployees(employees);
manager.persist(company1);

transaction.commit();

} finally {
closeConnection();
}
}

TILOTTAM ZOPE 96
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
c. many to one :-
T1 T2
R1
R1
R2

R3
R2
R4

1. When more than one record from table one are related to exactly one record from
Table 2 then the relationship between the 2 tables is considered to be many to one
relationship
2. The many to one relationship follows only the unidirectional relationship.

• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="ManyToOne">

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?
createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />

TILOTTAM ZOPE 97
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
</properties>
</persistence-unit>
</persistence>

• TrainDTO.java :-
package com.jspiders.hibernatemanytoone.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class TrainDTO {
@Id
private int id;
private String name;
private int train_no;
}

• PassengerDTO.java :-
package com.jspiders.hibernatemanytoone.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import lombok.Data;
@Data
@Entity
public class PassengerDTO {
@Id
private int id;
private String name;
private int age;
private int seat_no;
@ManyToOne
private TrainDTO train;

TILOTTAM ZOPE 98
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
• PassTrainDAO.java :-
package com.jspiders.hibernatemanytoone.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernatemanytoone.dto.PassengerDTO;
import com.jspiders.hibernatemanytoone.dto.TrainDTO;
public class PassTrainDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("ManyToOne");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();
transaction.begin();
TrainDTO train = new TrainDTO();
train.setId(1);
train.setName("Chennai Express");
train.setTrain_no(12345);
manager.persist(train);
PassengerDTO passenger1 = new PassengerDTO();
passenger1.setId(1);
passenger1.setName("Minamma");

TILOTTAM ZOPE 99
J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
passenger1.setAge(25);
passenger1.setSeat_no(10);
passenger1.setTrain(train);
manager.persist(passenger1);
PassengerDTO passenger2 = new PassengerDTO();
passenger2.setId(2);
passenger2.setName("Thangabali");
passenger2.setAge(30);
passenger2.setSeat_no(20);
passenger2.setTrain(train);
manager.persist(passenger2);
transaction.commit();
} finally {
closeConnection();
}
}
}

d. many to many :-

T1 T2
R1 R1

R2 R2

R3 R3

R4 R4

1. When more than one record from Table 1 are related to more than one record from
Table 2 then the relationship between the tables is considered to be many to many
relationship
2. If the relationship is defined only for one of the tables then the relationship is set to
be unidirectional relationship
3. But if the relationship is defined for both the tables then the relationship is set to be
bidirectional relationship

TILOTTAM ZOPE 100


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
• persisitence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="ManyToMany">

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?
createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

• CustomerDTO.java :-\
package com.jspiders.hibernatemanytomany.dto;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import lombok.Data;
@Data
@Entity
public class CustomerDTO {
@Id
private int id;

TILOTTAM ZOPE 101


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
private String name;
private long contact;
private String city;
@ManyToMany
List<ProductDTO> products;

• ProductDTO.java :-
package com.jspiders.hibernatemanytomany.dto;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import lombok.Data;
@Data
@Entity
public class ProductDTO {
@Id
private int id;
private String name;
private String category;
private double price;
@ManyToMany(mappedBy = "products")
List<CustomerDTO> customers;

• CustomerProductDAO.java :-
package com.jspiders.hibernatemanytomany.dao;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernatemanytomany.dto.CustomerDTO;
import com.jspiders.hibernatemanytomany.dto.ProductDTO;
public class CustomerProductDAO {
private static EntityManagerFactory factory;

TILOTTAM ZOPE 102


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
private static EntityManager manager;
private static EntityTransaction transaction;
private static void openConnection() {
factory = Persistence.createEntityManagerFactory("ManyToMany");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}
private static void closeConnection() {
if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {

openConnection();

transaction.begin();

ProductDTO product1 = new ProductDTO();


product1.setId(1);
product1.setName("T-Shirts");
product1.setCategory("Clothing");
product1.setPrice(1500);

ProductDTO product2 = new ProductDTO();


product2.setId(2);
product2.setName("Perfume");
product2.setCategory("Grooming");
product2.setPrice(2500);

ProductDTO product3 = new ProductDTO();


product3.setId(3);
product3.setName("AC");
product3.setCategory("Electronics");

TILOTTAM ZOPE 103


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
product3.setPrice(25000);

CustomerDTO customer1 = new CustomerDTO();


customer1.setId(1);
customer1.setName("Shahrukh");
customer1.setContact(9875641203L);
customer1.setCity("Delhi");

CustomerDTO customer2 = new CustomerDTO();


customer2.setId(2);
customer2.setName("Salman");
customer2.setContact(9875641203L);
customer2.setCity("Mumbai");

CustomerDTO customer3 = new CustomerDTO();


customer3.setId(3);
customer3.setName("Amir");
customer3.setContact(9875641203L);
customer3.setCity("Mumbai");

List<ProductDTO> products1 = Arrays.


asList(product1, product2);
customer1.setProducts(products1);
manager.persist(customer1);

List<ProductDTO> products2 = Arrays.


asList(product2, product3);
customer2.setProducts(products2);
manager.persist(customer2);

List<ProductDTO> products3 = Arrays.


asList(product1, product3);
customer3.setProducts(products3);
manager.persist(customer3);
List<CustomerDTO> customers1 = Arrays.
asList(customer1, customer3);
product1.setCustomers(customers1);
manager.persist(product1);

List<CustomerDTO> customers2 = Arrays.


asList(customer1, customer2);

TILOTTAM ZOPE 104


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
product2.setCustomers(customers2);
manager.persist(product2);

List<CustomerDTO> customers3 = Arrays.


asList(customer2, customer3);
product3.setCustomers(customers3);
manager.persist(product3);

transaction.commit();

} finally {
closeConnection();
}
}
}

➢ Additional annotation in hibernate :-


Enuneration (ENUM)
a. @Table
b. @Column
c. @Generated value
d. @Join table

a. @Table :-
It is used to control and modify the properties of the table

b. @Column
It is used to control and modify the properties of a column in the table

c. @Generated value
It is used to generate a value for a column based on defined strategy there are 4
strategies for the value generation
1st Auto
2nd Identity
3rd Sequence
4th Table

TILOTTAM ZOPE 105


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="annotations">

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?

createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

• StudentDTO.java :-
package com.jspiders.hibernateannotations.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity

TILOTTAM ZOPE 106


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
@Table(name = "student")
public class StudentDTO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "name")
private String stud_name;
@Column(name = "percent")
private double percentage;
@Column(name = "city")
private String stud_city;

• StudentDAO.java :-
package com.jspiders.hibernateannotations.dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.jspiders.hibernateannotations.dto.StudentDTO;
public class StudentDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;

private static void openConnection() {


factory = Persistence.createEntityManagerFactory("annotations");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}

private static void closeConnection() {


if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {

TILOTTAM ZOPE 107


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
transaction.rollback();
}
}

public static void main(String[] args) {

try {
openConnection();

transaction.begin();

StudentDTO student = new StudentDTO();


student.setStud_name("Abhishek");
student.setPercentage(80.24);
student.setStud_city("Pune");

manager.persist(student);

transaction.commit();

} finally {
closeConnection();
}
}
}

d. JoinTable.java :-
➢ Format :-
JoinTable(name= “intermidiate Table_name”,
join columns = @Join_Coloumn
(refernceColumnName = “primarykey & currentable”),
inverseJoinColumns = @JoinColumn
(refernceColumnName = “primarykey & related inverse table”))

1. It is used to control and modify the properties of the intermediate table for an
example : if one company is related to many employees, then it will be one to
many relationship and intermediate table will be created
2. While definig the relationship the company entity class we can use the join table of
company as follows,

TILOTTAM ZOPE 108


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
@JoinTable(name= “comp_emp”,
join columns = @Join_Coloumn
(refernceColumnTableName = “ID”),
inverseJoinColumns = @JoinColumn
(refernceColumnName = “ID”))

➢ JPQL :-
1. JPQL stands for java persistence query language
2. As we know, hibernate writes its own queries and it follows hibernate query
language which is not understood by another ‘ORM’ tools
3. For an example, The MyBaties ‘ORM’ tool follows dynamic query language
4. Hence, This makes its default to migrate from one ORM to another in this case,
we can use jpql that can be handled by all the orm tools implemented in java
application

NOTE :-
• while writing a JPQL queries we do not use the table name and the column
name, instead use the classname and the propertyname resp.

• persistence.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="jpql">

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/weja1?

createDatabaseIfNotExist=true" />
<property name="javax.persistence.jdbc.user"
value="root" />
<property name="javax.persistence.jdbc.password"

TILOTTAM ZOPE 109


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL8Dialect" />
</properties>
</persistence-unit>
</persistence>

• TrainDTO.java :-
package com.jspiders.hibernatejpql.dto;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class TrainerDTO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String subject;

• TrainerDAO.java :-
package com.jspiders.hibernatejpql.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import com.jspiders.hibernatejpql.dto.TrainerDTO;
public class TrainerDAO {
private static EntityManagerFactory factory;
private static EntityManager manager;
private static EntityTransaction transaction;

TILOTTAM ZOPE 110


J2EE-NOTES
ORM(HIbERNATE)
------------------------------------------------------------------------------------------
private static Query query;
private static String jpqlQuery;

private static void openConnection() {


factory = Persistence.createEntityManagerFactory("jpql");
manager = factory.createEntityManager();
transaction = manager.getTransaction();
}

private static void closeConnection() {


if (factory != null) {
factory.close();
}
if (manager != null) {
manager.close();
}
if (transaction.isActive()) {
transaction.rollback();
}
}
public static void main(String[] args) {
try {
openConnection();

transaction.begin();

jpqlQuery = "from TrainerDTO";


query = manager.createQuery(jpqlQuery);
List<TrainerDTO> trainers = query.getResultList();

for (TrainerDTO trainer : trainers) {


System.out.println(trainer);
}

transaction.commit();
} finally {
closeConnection();
}
}

TILOTTAM ZOPE 111


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
1. Servlet is the only technology that can accept web request and generate web
response

➢ Web-request and Web-response :-


1. Whenever a specific resource is requested from the server through a url, it is
known as web-request
2. When the request is analyst and the excepted resource is given back to the client,
it is known as a web-response

➢ Browser :-
1. Browser is the only application that can be generated Web-request and accept
Web-response

NOTE :-
• For a feature in the web application to work it has complete one
‘request-response-cycle’

www.google.com web-request

servlet

web-response
client server
Web-response
Browser Homepage HTML

➢ Uniform resource locator(URL) :-


1. It is used to request a web resource from the server

❖ Format :-
protocol://host_or_domain:port_no/path_to_resource?query_string#fragment_id

protocol :-
It represents whether the web request is protocol dependent or protocol
independent

TILOTTAM ZOPE 112


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
host_or_domain :-
It is used to identify the server where the application is present

port_no :-
It is used to find the exact location of the application or the identified server

path_to_resource :-
It represents the exact location of the requested web-resource

query_string :-
The data sent to the url to the server travels in the form of query string in key &
value pair

fragment_id :-
1. It represents the id of the fragment currently loaded in the response
2. It is in the form of hexadecimal value

➢ web resource :-
1. Any file in the web application which can be given as a response to the client is
called as web resource
2. There are 2 types of web resources
a. static web-resource
b. dynamic web-resource

a. Static web-resource :-
1. The web resource whose contain doesn’t change is known as static web-resource
2. A Static web-resource is same response for each request
3. It is kept ready at the server site even before the request is made for it

b. Dynamic web-resource :-
1. A web resource whose contain is changing is known as a dynamic web resource
2. It provides a different response for each request
3. A dynamic resource is not kept ready before the request is made for it

➢ web application :-
1. The applications that consist of web resources is called as web applications

TILOTTAM ZOPE 113


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
2. The web applications in which all the web resources are static is called as static
web application
3. The web application in which even a single web resource is dynamic is called as
dynamic web application

➢ Servlets in java :-
In Java, Servlets can be considered as a special class

➢ Hierarchy of survlets :-
MyServlet

HttpServlet

Generic Servlet

Servlet ServletConfig.

➢ ways to create servlet :-


a. extends HttpServlet class
b. extends GenericServlet class

a. extends HttpServlet class :-


1. This is the 1st Way of creating servlet in java
2. If the servlet is created in this way then it is considered to be a protocol dependent
servelet

b. extends GenericServlet class :-


1. This is the 2nd way of creating the servlet in java
2. If a servlet is created in this way then it will be considered as a protocol
independent servlet
3. In this case, we need to provide the logic for the unimplemented methods such as
the life cycle method

TILOTTAM ZOPE 114


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
➢ Life cycle of servlet :-
init() 1st time
service() Nth time
distroy 1st time

➢ Steps to create dynamic web project :-


1. press ‘ctrl + N’ and search for (dynamic web project) & then click on next
2. provide the project name & then click on next until you get the ‘web-module’
window
3. In web-module window check box of generate web.xml ‘development descriptor’
and then click on finish.

➢ Configuring the project for servlet :-


1. Change the Java version of the project to 1.8
2. Add the survelet API jar file to the project Buildpath

➢ Steps to install apache tomcat server :-


1. Go to the Google & search for ‘apache tomcat server .9’
2. In the Apache Software foundation link go to the download section
3. In download page scroll down to find out the ‘core’ section
4. Bsed on the operating system select the appropriate zip file to download
5. Go to the C:drive and go to the ‘program file’ folder
6. Create a new folder by the name ‘ApacheSoftwareFoundation’ folder
7. Extract the contain from the downloaded zip file and move that contain to the
newly created apache software foundation folder
8. In the servers window, click on the link to create a new server
9. In the next window, search for ‘tomcatv9.0 server’ click on next
10.In the next window, click on the browse button
11.In the explorer window select the folder present inside Apache Software
Foundation folder then click on next & finish

TILOTTAM ZOPE 115


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
❖ request mapping :-
1. The process of handling over the incoming request to the responsible servelt file is
known as request mapping
2. It is done with the help of mapping methods

➢ Mapping methods :-
There are two mapping methods in the servlets,
a. doget() method
b. dopost() method

NOTE :-
• The execution logic of a servlet has to be given in either doget() or dopost()
• the doget() is implicitly called by every web request but the dopost() has to
be called as explicitly

➢ Creating servlet file :-


1. Press ‘ctrl + N’ and serach servlet
2. Select ‘web module’ inside that click next
3. In the new window provide the class name and click on next
4. In the next window review(url mapping section) and then click on finish

NOTE :-
• Creating a servlet file gives us a class file which is preconfigured as a servlet
• Creating a servlet in this way give us the additional advatages of @webservlet
• If a servlet is created in this way then it is not required to be configured in the
web.xml because the configuration is provided by the webservlet annotation

• MyServlet1.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet1 extends HttpServlet {

TILOTTAM ZOPE 116


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println("<h5>Welcome to MyServlet1<h5>");
}
}

• MyServlet2.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println("<h1>Welcome to MyServlet2 from doPost()</h1>");
}

@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}

TILOTTAM ZOPE 117


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
• Web.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<display-name>servlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.jspiders.servlet.servlets.MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>com.jspiders.servlet
.servlets.MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/hi</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>Date</servlet-name>
<servlet-class>com.jspiders.servlet.servlets.DateTimeServlet</servlet-class>
</servlet>

TILOTTAM ZOPE 118


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
<servlet-mapping>
<servlet-name>Date</servlet-name>
<url-pattern>/date</url-pattern>
</servlet-mapping>

</web-app>

• DateTimeServlet.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DateTimeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
resp.setHeader("Refresh", "1");
PrintWriter writer = resp.getWriter();
Date date = new Date();
writer.println("<h1>" + date + "</h1>");
}
}

❖ SetContentType() :-
1. This method is used to define what type of content will be displayed in the
response
2. For an example , if the response is suppose to display html content then we need to
set content type as ‘text/html’
3. This has to pass as a string argument to the method

❖ PrintWriter() :-
1. The object of this class is used to print any content on the browser as the response

TILOTTAM ZOPE 119


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
2. The object of this class can be obtain with the help of getWriter() from the
response object

❖ SetHeader() :-
This method is used to change or alter the response headers.

➢ Creating servlet file :-


1. Instead of creating a class file & then making it as a servlet file itself
2. If we create a servlet file directly then , we get a class which is preconfigured as a
servlet
3. In this case, we do not need to if the servlet configured in the web.xml file
4. The servlet configuration is given by the ‘@WebServlet’ annotation
5. This annotation defines what url pattern will the servlet response

• DemoServlet.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/demo")
public class DemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<h1>Welcome to demo servlet</h1>");
}
}

TILOTTAM ZOPE 120


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
• Form.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Name</title>
</head>
<body>
<form action="./name" method="get">
<table>
<tr>
<td>Enter Name :</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td><input type="submit" value="Enter"></td>
</tr>
</table>
</form>
</body>
</html>

• NameServlet.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/name")
public class NameServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

TILOTTAM ZOPE 121


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String name = request.getParameter("name");
writer.println("<h1>Welcome " + name + "..!!</h1>");
}
}

• EmpRegistration.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Employee Registration Page</title>
</head>
<body>
<form action="./emp" method="post">
<h3>EMPLOYEE REGISTRATION</h3>
<table>
<tr>
<td>NAME</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>CONTACT</td>
<td><input type="text" name="contact"></td>
</tr>
<tr>
<td>EMAIL</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>ADDRESS</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td><input type="submit" value="SUBMIT"></td>
</tr>
</table>
</form>
</body>

TILOTTAM ZOPE 122


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
</html>

• EmpRegistration.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/emp")
public class EmpRegistration extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String name = request.getParameter("name");
String contact = request.getParameter("contact");
String email = request.getParameter("email");
String address = request.getParameter("address");
writer.println("<h1>Welcome " + name + "..!!</h1>");
writer.println("<h3>Contact : " + contact + "</h3>");
writer.println("<h3>Email : " + email + "</h3>");
writer.println("<h3>Address : " + address + "</h3>");
}
}

• Skill.html :-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Technical Skills</title>
</head>
<body>

<form action="./skills" method="post">


<h1>TECHNICAL SKILLS</h1>

TILOTTAM ZOPE 123


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
<table>
<tr>
<td><input type="checkbox" name="skills" value="Java"></td>
<td>JAVA</td>
</tr>
<tr>
<td><input type="checkbox" name="skills" value="Webtech"></td>
<td>WEBTECH</td>
</tr>
<tr>
<td><input type="checkbox" name="skills" value="SQL"></td>
<td>SQL</td>
</tr>
<tr>
<td><input type="checkbox" name="skills" value="J2EE"></td>
<td>J2EE</td>
</tr>
<tr>
<td><input type="submit" value="SUBMIT"></td>
</tr>
</table>
</form>

</body>
</html>

• Skill.java :-
package com.jspiders.servlet.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/skills")
public class Skills extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

TILOTTAM ZOPE 124


J2EE-NOTES
SERvLET
------------------------------------------------------------------------------------------
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String[] skills = request.getParameterValues("skills");
writer.println("<h1>Your Technical Skills Are</h1>");
for (String skill : skills) {
writer.println("<h3>" + skill + "</h3>");
}
}
}

• MANIFEST.MF :-
Manifest-Version: 1.0
Class-Path:

NOTE :-
• Servlet is a deprecated technology as it forces us to write execute a java
to provide even a small HTML response

TILOTTAM ZOPE 125


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
1. JSP stands for Jakarter Server Pages
2. The JSP technology build over the servlet framwork itself
3. Hence the JSP internally implements servlet itself
4. JSP allows us to focus more than the HTML logic rather than the Java code

Servlet JSP

Java HTML

HTML Java

java jsp
5. The JSP file provides us the structure of HTML and allows us to include Java logic
in it

➢ Basic JSP file structure :-


• DemoJsp1.html :-
<%@ page language="java" contentType="text/html;
charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Demo Page</title>
</head>
<body>
<h1>Hello from JSP</h1>
</body>
</html>

TILOTTAM ZOPE 126


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
➢ Life cycle of JSP :-
translation 1st time (before 1st)

jsp-init() 1st time

jsp-service() nth time

jsp-destroy() 1st time

➢ Servlet container :-
1. The servlet container is a component in servlet framework which is responsible to
the manage the life cycle of servlet and JSP
2. It is also responsible to translate a JSP file into the corresponding servlet class file

➢ Translation phase :-
1. A JSP file has to be converted in the corresponding servlet
2. Class file before it start class file before it start it lifecycle this process of the
translation is done only one before the first life cycle of JSP

❖ jsp_init() :-
This method is invoked when the JSP is initialized this method is called as only
once in each life

❖ jsp_service() :-
1. This method is called nth number of times in each lifecycle
2. It is invoke when the JSP is called for execution

❖ jsp_destroy() :-
This method is invoked when the JSP is done with its execution this method is
called as only once in each life cycle

TILOTTAM ZOPE 127


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
NOTE :-
• The Java logic can be included inside the HTML body with the help of JSP tags

➢ JSP tags :-
1. There are five types of tags in JSP are as follows ;
a. scriptlet tag <% %>
b. Declaration tag <%! %>
c. Expression tag<%= %>
d. Directive tag <%@ %>
e. Action tag <jsp: >

a. scripted tag <% %> :-


All the Java execution logic can be written with the help of scripted tag

b. Declaration tag <%! %>


It is used to declare variable or object related to Java

c. Expression tag<%= %>


It is used to print or display the value or variable related to Java

d. Directive tag <%@ %>


Directive to tag is used to include Java statements line ‘import’

e. Action tag <jsp: >


Action tag is used to in order to perform certain action regarding the JSP pages

• TagDemo1.jsp :-
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:include page="TagDemo2.jsp" />
<!DOCTYPE html>
<html>

TILOTTAM ZOPE 128


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
<head>
<meta charset="UTF-8">
<title>Tag Demo Page</title>
</head>
<body>
<div align="center">
<h1>Tag Demo Jsp 1</h1>
<%!List<Integer> list = new ArrayList();%>
<%
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
%>
<%
for (Integer num : list) {
%>
<h3><%=num%></h3>
<%
}
%>
</div>
</body>
</html>

• TagDemo2.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tag Demo 2</title>
</head>
<body>

<div align="center">
<h1>Tag Demo Jsp 2</h1>

TILOTTAM ZOPE 129


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
<%!int a = 10;
int b = 20;
int c = 0;%>

<%!public int add() {


return a + b;
}%>

<%
c = add();
%>

<h3><%=c%></h3>
</div>

</body>
</html>

• DemoJSP1.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!String url = "https://www.google.co.in"; %>
<%response.sendRedirect(url); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP PAGE 1</title>
</head>
<body>
<div align="center">
<h1>HELLO FROM JSP 1</h1>
<form action = “./DemoJSP2.jsp”>
<input type = “submit” value = “Go To Page”>
</form>
</div>
</body>
</html>

TILOTTAM ZOPE 130


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
• DemoJSP2.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP PAGE 2</title>
</head>
<body>
<div align="center">
<h1>HELLO FROM JSP 2</h1>
<form action = “./DemoJSP1.jsp”>
<input type = “submit” value = “Go To Page”>
</form>
</div>
</body>
</html>

• StudentRegistration.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration Page</title>
</head>
<body>
<div align="center">
<form action="./StudentDetails.jsp" method="post">
<fieldset>
<legend style="margin: auto;">StudentRegistration</legend>
<table>
<tr>
<td>NAME</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>EMAIL</td>

TILOTTAM ZOPE 131


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>CONTACT</td>
<td><input
type="text"name="contact"></td>
</tr>
<tr>
<td>CITY</td>
<td><input type="text" name="city"></td>
</tr>
</table>
</fieldset>
<input style="margin-top: 2px;" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>

• StudentDetails.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String contact = request.getParameter("contact");
String city = request.getParameter("city");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Details Page</title>
</head>
<body>
<div align="center">
<fieldset>
<legend style="margin: auto;">Student Details</legend>
<table>
<tr>

TILOTTAM ZOPE 132


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
<td>NAME :</td>
<td><%=name%></td>
</tr>
<tr>
<td>EMAIL :</td>
<td><%=email%></td>
</tr>
<tr>
<td>CONTACT :</td>
<td><%=contact%></td>
</tr>
<tr>
<td>CITY :</td>
<td><%=city%></td>
</tr>
</table>
</fieldset>
</div>
</body>
</html>

f. <jsp: include> tag


This action tag is used to include one JSP page in another JSP page

• TagDemo1.jsp :-
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:include page="TagDemo2.jsp" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Tag Demo Page</title>
</head>
<body>
<div align="center">
<h1>Tag Demo Jsp 1</h1>
<%!List<Integer> list = new ArrayList();%>

TILOTTAM ZOPE 133


J2EE-NOTES
JSp
------------------------------------------------------------------------------------------
<%
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
%>
<%
for (Integer num : list) {
%>
<h3><%=num%></h3>
<%
}
%>
</div>
</body>
</html>
g. <jsp: forward> tag
1. This action tag is used to forward the incoming web request from one JSP to
another JSP
2. In this case, the client (browser) is unawear that the request was forwarded and
some other resources is providing the response

• DemoJSP1.jsp :-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%!String url = "https://www.google.co.in"; %>
<%response.sendRedirect(url); %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP PAGE 1</title>
</head>
<body>
<div align="center">
<h1>HELLO FROM JSP 1</h1>
</div>
</body>
</html>

TILOTTAM ZOPE 134


J2EE-NOTES
SpRING
(SpRING FRAMEwORk)
------------------------------------------------------------------------------------------
Spring core ------------------------------- features of spring F/W
Spring MVC ----------------------------- monolithic
Spring Rest ------------------------------ RESTful API’s
Spring Boot ------------------------------ web services / microservices

1. Spring is an open source framework which is used to develop enterprise


application
2. Spring framework is dedicated for Java development
3. Spring framework helps us to develop monolithic as well as server side application
4. Spring framework provides the infrastructure for enterprise Java development

sever-side application client-side application

BackEnd FrontEnd

Monolithic Application

5. The backend logic is considered as the server side logic whereas the frontend logic
is considered as the client side logic
6. When both the server and client site logics are develop in a single application then
it is known as monolithic architecture
7. The monolithic architecture is recommended while developing a small scale
application which does not demand high server strength
8. When the application demands high server strength, the client side server
architecture is recommended

TILOTTAM ZOPE 135


J2EE-NOTES
SpRING
(SpRING FRAMEwORk)
------------------------------------------------------------------------------------------
9. In the client side server architecture the client side and server side logic are present
in two different application
10.Hence, the client server architecture allows us to develop and deploy the client side
application and the server side application independently

TILOTTAM ZOPE 136


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
1. The spring core module helps us to understand the features of spring framework
2. The two key features of spring framework are
a. IOC (Inversion of control)
b. Dependency injection

a. IOC (Inversion of control) :-


1. In the spring framework the programmer is no-longer in control of object creator
2. The objects in the spring framework are called as ‘beans’
3. The component known as spring container or IOC container is responsible for the
bean creation as well as the managing the lifecycle of the beans
4. The spring container component takes the help of beam factory in order to create
the means the BeanFactory in order to create the beans
5. The BeanFactory creates the bean according to the user defined configure only
when required

b. Dependency injection :-
1. If a class depends upon another class objects for its own object creation then such
class is called as dependent class
2. In class which it depends upon can we called as dependency class
3. The process of injecting the object of the dependency class into the object of
independent class is known as dependency injection dependency injection
4. dependency injection is performed by the spring container component

➢ Bean configuration :-
1. The process of defining or declaring the values for object properties is called as
bean configuration
2. In spring framework the bean configuration can be done in two ways,
a. XML configuration
b. Annotation configuration

a. XML configuration :-
1. For demonstrating the bean creation process we need to create an xml file which
will hold the value for the bean property
2. For this purpose, we need to create the maven project with the arc-type as quick
start

TILOTTAM ZOPE 137


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
➢ Dependencies required for spring core :-
a. Spring Core
b. Spring context
c. Lombok

NOTE :-
• The XML configuration file have to be created immediately under
‘src/main/java’ source folder

➢ Annotation configuration :-
1. In anotation configuration we need to make use of config class to provide a logic
for bean configuration
2. We need to make use of @Bean annotation for the configuration
3. In the config class there will be a method which will be responsible to create the
bean of the required class

• Student config.java :-
<?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.xsd">

<bean class="com.jspiders.springcorexml.beans.StudentBean"
name="student1">
<property name="id">
<value>1</value>
</property>
<property name="name" value="Swapnil" />
<property name="city" value="Pune" />
</bean>

<bean class="com.jspiders.springcorexml.beans.StudentBean"
name="student2">
<constructor-arg name="id">
<value>2</value>

TILOTTAM ZOPE 138


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
</constructor-arg>
<constructor-arg name="name" value="Swapnali"/>
<constructor-arg name="city" value="Mumbai"/>
</bean>

</beans>

• StudentBean.java :-
package com.jspiders.springcorexml.beans;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentBean {
private int id;
private String name;
private String city;
}

• StudentMain.java :-
package com.jspiders.springcorexml.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jspiders.springcorexml.beans.StudentBean;
public class StudentMain {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("StudentConfig.xml");
StudentBean student1 = (StudentBean) context.getBean("student1");
System.out.println(student1);
StudentBean student2 = (StudentBean) context.getBean("student2");
System.out.println(student2);
((ClassPathXmlApplicationContext)context).close();
}
}

TILOTTAM ZOPE 139


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
@Component :-
1. This is a class level annotation and it is used to make the annotated class eligible
for the bean creation
2. If a class is mark with this annotation then a spring container will consider this
class for the bean creation process

@ComponentScan :-
It is a class level annotation which enable the annotated class to scan for
component in the mentioned class or a package

@AutoWired :-
It is a property level annotation which is used to mark the property for dependency
injection

@Value :-
It is a property level annotation which is used to provide the property values
implicitly during bean creation

• CarBean.java :-
package com.jspiders.springcoreannotation.beans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import lombok.Data;
@Data
public class CarBean {
@Value("1")
private int id;
@Value("Mahindra")
private String brand;
@Value("XUV")
private String model;
@Value("MH12AB1234")
private String regno;
@Autowired
private DriverBean driver;
}

TILOTTAM ZOPE 140


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
• DriverBean.java :-
package com.jspiders.springcoreannotation.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.Data;
@Data
@Component
public class DriverBean {
@Value("1")
private int id;
@Value("Karan")
private String name;
@Value("8756941230")
private long contact;
}

• CarDriverConfig.java :-
package com.jspiders.springcoreannotation.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.jspiders.springcoreannotation.beans.CarBean;
@ComponentScan(basePackages = "com.jspiders.springcoreannotation")
public class CarDriverConfig {
@Bean("car1")
public CarBean getCar() {
return new CarBean();
}
}

• CarDriverMain.java :-
package com.jspiders.springcoreannotation.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.jspiders.springcoreannotation.beans.CarBean;
import com.jspiders.springcoreannotation.config.CarDriverConfig;
public class CarDriverMain {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(CarDriverConfig.class);

TILOTTAM ZOPE 141


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
CarBean car1 = (CarBean) context.getBean("car1");
System.out.println(car1);
((AnnotationConfigApplicationContext)context).close();
}
}

• EmployeeBean.java :-
package com.jspiders.springcoreannotation.beans;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmployeeBean {
private int id;
private String name;
private String email;
}

• EmployeeConfig.java :-
package com.jspiders.springcoreannotation.config;
import org.springframework.context.annotation.Bean;
import com.jspiders.springcoreannotation.beans.EmployeeBean;
public class EmployeeConfig {
@Bean("emp1")
public EmployeeBean getEmployee() {
EmployeeBean emp1 = new EmployeeBean();
emp1.setId(1);
emp1.setName("Pankaj");
emp1.setEmail("[email protected]");
return emp1;
}
@Bean("emp2")
public EmployeeBean getEmployee2() {
EmployeeBean emp2 = new EmployeeBean
(2, "Pooja", "[email protected]");
return emp2;
}

TILOTTAM ZOPE 142


J2EE-NOTES
SpRING
(SpRING cORE)
------------------------------------------------------------------------------------------
}

• EmployeeMain.java :-
package com.jspiders.springcoreannotation.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.jspiders.springcoreannotation.beans.EmployeeBean;
import com.jspiders.springcoreannotation.config.EmployeeConfig;
public class EmployeeMain {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(EmployeeConfig.class);
EmployeeBean emp1 = (EmployeeBean)context.getBean("emp1");
System.out.println(emp1);
EmployeeBean emp2 = (EmployeeBean)context.getBean("emp2");
System.out.println(emp2);
((AnnotationConfigApplicationContext)context).close();
}
}

TILOTTAM ZOPE 143


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
1. MVC stands for model view controller
2. Spring MVC is used to develop monolithic applications in spring framework
3. MVC provides a detailed architecture for the development of the application

NOTE :-
• MVC is also considered as an architecture design pattern

➢ MVC architecture :- BackEnd/Server-side


Logic

www.google.com web-request controller model DB

Client web-response FrontEnd/


View Client-side Logic

controller :-
1. The controller component is responsible to handle all the incoming web-request
2. It decides that which model should be implemented for each incoming request
specially
3. It also decides which view has to be given back as the web-response

model :-
1. The model component can be considered as the BackEnd of the application
2. The model is responsible to communicate with the database and return the process
data (model data) back to the controller
3. It holds all the operation and validation logic to be perform all the data

View :-
1. The view component is considered as the FrontEnd of the application
2. It consists of all the view pages (HTML or JSP) required for the application
3. It receives the model the model data from the controller and it is responsible to
display the same in the web response

TILOTTAM ZOPE 144


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
➢ Spring MVC Architecture :- Handler Mapping

www.google.com web-request Dispatcher Controller Service


Servlet

Client
DB POJO Repositary
Web-Response

View-Resducer

View

➢ Creating a project for MVC :-


1. Create a new Maven project of the arc-type ‘web-app’ of the version 1.4
2. Configure the project for the java version and add the required dependencies.
3. To provide a structure format for the FrontEnd logic, create a general folder inside
the ‘WEB-INF’ folder by the name ‘views’ all the FrontEnd pages will be located
inside this folder only
4. To provide a structure format to the BackEnd logic create the controller and the
model layers as the packages and provide the required annotations to identify the
layers
5. Create an xml file inside the ‘WEB-INF’ folder by the name
‘dispatchers/servlet.xml’

➢ Dependencies required for spring MVC :-


1. springweb MVC (5.3.20)
2. hibernate core relocation (5.6.14)
3. hibernate entity manager relocation (5.6.14)
4. spring ORM (5.3.20)
5. mysql connector/J (8.0.32)
6. javax-servlet-API (3.1.0)
7. project lombok (1.18.22)

TILOTTAM ZOPE 145


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
➢ Structure of MVC project :-
V Spring mvc
> Deployment Descriptor : Archtype Created
V <src/main/java
>Deployment Descriptor : Archtype Created
>com.jspiders.springmvc
> com.jspiders.springmvc.controller
>com.jspiders.springmvc.pojo
>com.jspiders.springmvc.repository
> com.jspiders.springmvc.service
>src/test/java
V src/main/resources
>Deployment Descriptor.Archtype.created
V >META-INF
persisitance.xml
>libraries
>Deployment Resources
V Deployment Resources
V >src
V >main
> >java
> >resources
> >web-app
V >Web-INF
dispatcher_servlet.xml
web.xml
index.jsp
>test
>target

TILOTTAM ZOPE 146


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
@controller :-
It is a class lavel annotation which is to mark a class to be identified as a controller

@service :-
It is a class level annotation which is used to mark a class to be identified as a
service layer

@repository :-
It is a class level annotation which is used to mark the class to be identified as the
repository layer

NOTE :-
• The @controller, @service, @repository annotation are the combination of 4
different annotations
@Target (Value = {Type})
@Component
@Rotention (Value = RUNTIME)
@Documented

➢ Handler mapping configuration :-


1. The configuration for this components has to be given in the
‘dispatcher/Servlet.XML’ file

<Context : annotation_config/>
<Context : component_scan
base-pacakge = “com.jspiders.springmvc”>

➢ View resolver configuration :-


1. This component has to be configured in the ‘dispatchers/servlet.xml’
2. This component helps to locate the view pages
<bean
class =
“org.SpringFramework.Web.Servlet.View
.InternalResourceViewResolver”>
<property name = “prefix” value = “/WEB-INF/View”/>
<property name = “suffix” value = “.jsp”/>

TILOTTAM ZOPE 147


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
</bean>

➢ Dispatcher-servlet configuration :-
1. This component has to be configured in the ‘web.xml’ file.
<servlet>
<servlet-name> dispatcher </servlet-name>
<servlet-class>
org.springframework.web-servlet.DispatcherServlet
</servlet-name>
</servlet>
<servlet-mapping> dispatcher </servlet-mapping>
<url-mapping>/</url-pattern>
</servlet-mapping>

➢ Mapping method :-
1. Get mapping() :-
In spring MVC the controller has to accept the web-request for the application

2. @GetMapping() :-
a. This annotation helps to controller to accept the web-request which follows the
‘get()’
b. The spring argument given to this annotation is considered as the url pattern for the
request
ex. @GetMapping(“/home”)

3. PostMapping() :-
a. The @post mapping annotation helps the controller to accept a web request that
follows the post()
b. The spring argument given to this annotation is considered as the url pattern for
the request
ex. @PostMapping(“/add”)

4. @RequestParam() :_
a. This anotation allows us to fatch the value of a specific parameter present in the
web-request
b. The value can be fatch by this annotation by providing the name and datatype of
the parameter

TILOTTAM ZOPE 148


J2EE-NOTES
SpRING
(SpRING Mvc)
------------------------------------------------------------------------------------------
5. ModelMap :-
a. This class helps us to map the data from the BackEnd in the FrontEnd
b. It means the object of the class allows us to send data from controller to the view
pages
c. It is done with the help of a method named as ‘addAttribute()’
d. This method accept various types of argument as it is an overloaded method one of
the method header allows us to provide 2 arguments
i. Spring value which is considered to be the key which will help to identify the
data in the JSP
ii. The second argument will be the actual data

6. Session() :-
a. It is the time interval between the loging and logout time
b. The session object has to be given to the browser
c. The session is represented by the object of ‘httpSession’ interface
d. The object of the http session is obtained with the help of the ‘getSession()’ present
in ‘httpServletRequest’ interface

7. @session attribute() :-
a. This annotation is used to access the value of the attribute assigned to the session
object
b. The attribute is assigned to the session after its creation, so that it can be accessed
throughout the application
c. It can be done by mentioning the session attribute name and the entity for which
the session of created

8. httpsession() :-
The http session interface is required to create a session once after the object has
successfully started its active time

TILOTTAM ZOPE 149


J2EE-NOTES
SpRING
(SpRING REST)
------------------------------------------------------------------------------------------
1. Spring rest represented state transfer
2. Spring rest is used to develop only the server side application
3. Hence a spring rest we do not have to configure the web component has in spring
rest the front end logic will not be included
4. In this case the server side application and client side application are developed as
a separate and independent application
5. As the server side application helps to establish communication between the client
side application and the database, hence we can say that it behaves as an API
6. In spring rest, each controller is responsible to handle a specific request and
provide the response in the form of an object

NOTE :-
• The data of the application has to travel from the front end application to the
back end application and vice versa
• Hence it has to be in format which can be understood and process by both
the applications

➢ JSONS(javascript object notations) :-


1. The data in JSONS represented in the form of key value pair
2. Once Jason’s object is enclosed within the opening and closing curly brackets {}
3. The properties of the object are represented as key and value and properties are
separated by ( , ) comma
4. The key of property is enclosed within opening and closing (“ ”)
5. The value of the property may or may not be enclosed in (“ ”) depending on its
data type
6. The value and key are separated by (:)
7. Ex.,
{
“id” : I,
“name” : “Tilottam”,
“contact” : 7798495977
“email” : [email protected]
“designation” : “Software Developer”
“salary” : 50000
}

TILOTTAM ZOPE 150


J2EE-NOTES
SpRING
(SpRING REST)
------------------------------------------------------------------------------------------
8. In spring rest each controller should be capable of performing the process of
marshalling & unmarshalling
9. Marshalling is the process of converting java object into JSONS object
10.Unmarshalling is the process of converting JSONS object to java object

marshalling
java JSONS
object
unmarshalling

➢ Creating the project for spring REST :-


1. The spring rest project will be created in the same way as spring MVC
2. As spring rest could not include the FrontEnd logic hence, do not need to create the
‘views’ folder
3. Also we do not need to configure to ViewResolver component in dispatcher servlet
4. The controller layer must be capable to provide response body

➢ Dependencies required for spring REST :-


1. In addition to dependencies from spring MVC we need to include following two
dependency as well
a. jackson core 2.13.3
b. jackson Databind 2.13.3

Marshalling :-

produce = {Mediatype.APPLICATION_JSON_VALUE}

Unmarshalling :-

consumes = {MediaType.APPLICATION_JSONS_VALUE}

ResponseEntity :-
This class is used to spring rest controller to provide the response as an object
hence the controller has to return the object of ResponseEntity class

TILOTTAM ZOPE 151


J2EE-NOTES
SpRING
(SpRING REST)
------------------------------------------------------------------------------------------
JsonsInclude :-
1. This annotation helps us to include only the required property from the object in
the Jsons dates
2. For example, if we want to include only the properties of object which are not null
then it can be done as mentioned below,

@JsonsInclude(JsonsInclude.Include.NON_NULL)

API testing tool :-


1. The API testing tool is used to test the working of API’s in the BackEnd
application
2. It can be used to send request to the server side application and display the
response given by it

NOTE :-
• The most popular API tasting tool is Postman

➢ Mapping Method In Postman :-


a. Get Retrive

b. Post Create

c. Put Update

d. Delete Delete

1. @ResponseBody :-
This annotation is used to fatch the object body from the web-request
It can be done by mentioning the name of the entity whose object has to be fatch

2. @PathVariable :-
This annotation is used to fetach the value of the variable present in the request or
url path

TILOTTAM ZOPE 152


J2EE-NOTES
SpRING
(SpRING REST)
------------------------------------------------------------------------------------------
3. @RestController
1. In spring rest in the controller class has to be annotated with this annotation as the
controller will be responsible to provide respons body as well
2. It is possible because these annotation internally contain @Controller, and
@ResponseBody along with few other annotation

TILOTTAM ZOPE 153


J2EE-NOTES
SpRING
(SpRING bOOT)
------------------------------------------------------------------------------------------
1. Spring boot module is same as similar to spring rest But it has its own advantages
2. The springboot project does not need external server as each springboot project
comes within embedded server
3. Hence the server configuration files such as web.XML and dispatcher-servlet.xml
are not required
4. Springboot also support dates JPA which allows us make use of predefined
repositories to perform all the CRUD operation all are entity
5. The configuration or property of hibernate has to be configured as project
properties itself
6. Hence we do not need to perform any hibernate logic in the repository And also we
don’t need to create persistence.xml file
7. All the project properties are defined in the application.properties file

NOTE :-
• To create springboard project we can follows one of two ways mentioned
below,
a. Creating a project online with the help of Spring Initializer and then and
then downloading and importing project in the Eclipse IDE
b. Creating spring starter project in the ‘spring tool side site’ (STS)

NOTE :-
• STS it is dedicately use for springboot development

➢ Dependencies for SpringBoot :-


1. Spring boot web
2. Spring data JPA
3. My sql connector
4. Project Lombok
5. Spring Devtools

TILOTTAM ZOPE 154


J2EE-NOTES
SpRING
(SpRING bOOT)
------------------------------------------------------------------------------------------
➢ adding the project properties :-
1. Server.port =
2. Spring.datasource.url =
3. Spring.datasource.username =
4. Spring.datasource.password =
5. Spring.jpa.hibernate.ddl-auto =
6. Spring.jpa.show-sql =
7. Spring.jpa.properties.hibernate.dialet =

NOTE :-
• To run SpringBoot project we need to run it as “SpringBoot App”

TILOTTAM ZOPE 155

You might also like