You are on page 1of 36

CSI3018- Advanced Java

CSI3018- Advanced Java

1
Fall-Semester 2022-2023 Dr. A Justin Gopinath SCOPE
CSI3018- Advanced Java

Syllabus
Module:1 JDBC Programming 4 hours
JDBC Architecture, Creating simple JDBC Application, Statements, ResultSet Operations, Batch
Updates in JDBC, Creating CRUD Application, Using Rowsets Objects, Managing Database
Transaction.
Module:2 Servlet API and JSP – Overview 4 hours
Servlet Introduction, Working with Servlet Context and Servlet Config Objects, Response and
Redirection, Filter API, Hidden Form Fields and URL Rewriting, Servlet Events – Context Level and
Session Level. JSP Architecture, JSP Scripting Elements, JSP Directives, JSP Action, JSP Implicit
Objects, JSP Standard Tag Libraries, JSP Custom Tag
Module:3 J2EE and Web Development 4 hours
Java Platform, J2EE Architecture Types, Java EE Containers, Servers in J2EE Application, Web
Application Structure, Web Containers and Web Architecture Models. Request Processing in Web
Application.
Module:4 Advance Networking 4 hours
Introduction of Socket, Types of Socket, Socket API, TCP/IP client sockets, URL,
TCP/IP server sockets, Datagrams, java.net package Socket, ServerSocket, InetAddress,
URLConnection, RMI Architecture, Client Server Application using RMI

2
SCOPE
CSI3018- Advanced Java

Syllabus
Module:5 Hibernate 4 hours
Introduction to Hibernate, Exploring Architecture of Hibernate, O/R Mapping with Hibernate,
Hibernate Annotation, Hibernate Query Language, CRUD Operation using Hibernate API.

Module:6 Java Web Frameworks: Spring MVC 4 hours


Spring Introduction, Spring Architecture, Spring MVC Module, Life Cycle of Bean Factory,
Constructor Injection, Dependency Injection, Inner Beans, Aliases in Bean, Bean Scopes, Spring
Annotations, Spring AOP Module, Spring DAO, Database Transaction Management, CRUD
Operation using DAO and Spring API.

Module:7 Java Server Faces 4 hours


Features of JSF, JSP Architecture, JSF request processing Life cycle, JSF Elements, JSF
Expression Language, JSF Standard Component, JSF Facelets Tag, JSF Convertor Tag, JSF Validation
Tag, JSF Database Access, JSF PrimeFaces.

Module:8 Recent Trends 2 hours

3
SCOPE
CSI3018- Advanced Java

Syllabus
Text Books
1.Core and Advanced Java, Black Book, Recommended by CDAC, Revised and Upgraded by
Dreamtech Press, 2018
2.Richard M Reese, Learning Network Programming with Java, Packt publisher, 2015

Reference Books
1.Craig walls ,Spring in Action, 5th edition, Manning Publication,2020.
2.Pankaj B. Brahmankar, Advanced JAVA Programming, Tech Neo Publications, 2019.

4
SCOPE
CSI3018- Advanced Java

Course Assessments - Rubrics


Assessment includes
• Two Continuous Assessment Tests (CAT)
• 1 Digital assignment
• 2 Quizzes
• Final Assessment Test (FAT)

5
SCOPE
CSI3018- Advanced Java

Lab Assessments - Rubrics


Assessment includes
• Assessment – 1
• Assessment – 2
• Mid-term Assessment
• Assessment – 4
• Assessment – 5
• Final Assessment Test (FAT)

6
SCOPE
CSI3018- Advanced Java

Module–I
JDBC Programming

7
SCOPE
CSI3018- Advanced Java

Review – Core Java


Write a Java program to print “ Welcome to Advanced Java Course”.

Write a Java program to find a largest integer of N integers.

Write a Java program for creating one base class for student personal details
and inherit those details into the sub class of student Educational details
(UGStudent, PGStudent) to display complete student information

8
SCOPE
CSI3018- Advanced Java

Assessment - 1
Install and configure NetBeans IDE for developing web
application in your local machine

Install NetBeans IDE


Install and configure MySQL Server
Install and configure Apache Tomcat Server

9
SCOPE
CSI3018- Advanced Java

JDBC Connectivity
• JDBC is: Java DataBase Connectivity
– is a Java API for connecting programs written in Java to the data in
relational databases.
– consists of a set of classes and interfaces written in the Java programming
language.
– provides a standard API for tool/database developers and makes it possible
to write database applications using a pure Java API.
• JDBC:
– establishes a connection with a database
– sends SQL statements
– processes the results.

10
SCOPE
CSI3018- Advanced Java

JDBC API
• The JDBC API supports both two-tier and three-tier models for
database access.
• Two-tier model -- a Java applet or application interacts directly with
the database.
• Three-tier model -- introduces a middle-level server for execution of
business logic:
– the middle tier to maintain control over data access.
– the user can employ an easy-to-use higher-level API which is
translated by the middle tier into the appropriate low-level calls.

11
SCOPE
CSI3018- Advanced Java

JDBC Architecture
Java Application

JDBC driver manager

JDBC/native JDBC/ODBC JDBC Driver JDBC middleware


bridge bridge (DBMS Specific) (various DBMS)

Native driver
ODBC Driver
(DBMS specific)

DBMS 12
SCOPE
CSI3018- Advanced Java

JDBC Steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set
Object
6. Processing the Result Set
7. Closing the Connection

13
SCOPE
JDBC API 4.0 mainly provides 2 important packages:
CSI3018- Advanced Java
•java.sql
•javax.sql

1: Importing Packages
JDBC API 4.0 mainly provides 2 important packages:
i) java.sql - package provides classes and interfaces to perform most
of the JDBC functions like creating and executing SQL queries
ii) javax.sql - a JDBC extension API and provides server-side data
access and processing in Java Program.

//Import packages
import java.sql.*; //JDBC packages
import java.math.*;
import java.io.*;

14
SCOPE
CSI3018- Advanced Java

2: Registering JDBC Drivers


 load/register the driver in the program before connecting to the Database.
 You need to register it only once per database in the program.

 load the driver in the following 2 ways:


i) Class.forName()
ii) DriverManager.registerDriver()
DB Name JDBC Driver Name

MySQL com.mysql.jdbc.Driver

Oracle oracle.jdbc.driver.OracleDriver

Microsoft SQL Server com.microsoft.sqlserver.jdbc.SQLServerDriver

MS Access net.ucanaccess.jdbc.UcanaccessDriver
15
SCOPE
CSI3018- Advanced Java

2: Registering JDBC Drivers


i) Class.forName()
the driver’s class file loads into the memory at runtime. It implicitly loads
the driver. While loading, the driver will register with JDBC automatically

Types of Drivers:
1. JDBC-ODBC bridge driver - any database. performance degraded
2. Native-API driver (partially java driver) - Native API driver uses the client-
side libraries of the database, Native driver needs to be installed on the each
client machine
3. Network Protocol driver (fully java driver) – uses middleware (application
server) that converts JDBC calls directly or indirectly into the vendor-specific
database protocol
4. Thin driver (fully java driver) - converts JDBC calls directly into the vendor-
specific database protocol. Better performance than all other drivers
16
SCOPE
CSI3018- Advanced Java

2: Registering JDBC Drivers


(ii) DriverManager.registerDriver()
DriverManager is an inbuilt class that is available in the java.sql package.
 It acts as a mediator between Java application and database which you want to connect.
The main function of DriverManager is to load the driver class of the Database and create a
connection with DB.

Public static void registerDriver(driver) – This method will register the driver with the Driver
Manager. If the driver is already registered, then it won’t take any action.
 It will throw SQLException if the database error occurs.
 It will throw NullPointerException if the driver is null.

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())

17
SCOPE
CSI3018- Advanced Java

3: Opening connection to a Database


 DriverManager class has the getConnection method, we will use this
method to get the connection with Database.
getConnection(URL,username,password);
– It has 3 parameters URL, username, password.
Database Connection String/DB URL
MySQL jdbc:mysql://HOST_NAME:PORT/DATABASE_NAME

Oracle jdbc:oracle:thin:@HOST_NAME:PORT:SERVICE_NAME

Microsoft SQL Server jdbc:sqlserver://HOST_NAME:PORT;DatabaseName=< DATABASE_NAME>

Example:
Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,System,Pass123@)

18
SCOPE
CSI3018- Advanced Java

4. Creating a Statement Object


(i) Create Statement
 create the statement object that runs the query with the connected
database.
 use the createStatement method of the Connection class to create the
query.
There are 3 statement interfaces are available in the java.sql package.
i) Statement - used to implement simple SQL statements with no parameter
ii) Prepared Statement - used to implement parameterized and precompiled SQL statements.
iii) Callable Statement - used to implement a parameterized SQL statement that invokes
procedure or function in the database

Statement statemnt1 = conn.createStatement();


String select_query = “Select * from states where state_id = 1”;
PreparedStatement prpstmt = conn.prepareStatement(select_query);
CallableStatement callStmt = con.prepareCall("{call procedures(?,?)}");
19
SCOPE
CSI3018- Advanced Java

5. Executing a Query
There are 4 important methods to execute the query in Statement interface
1. ResultSetexecuteQuery(String sql) - used to execute the SQL query and retrieve the values
from DB
2. int executeUpdate(String sql) - used to execute value specified queries like INSERT, UPDATE,
DELETE (DML statements)
3. Boolean execute(String sql) - used to execute the SQL query. It returns true if it executes the
SELECT query. And, it returns false if it executes INSERT or UPDATE query
4. int []executeBatch() - to execute a batch of SQL queries to the Database and if all the queries
get executed successfully, it returns an array of update counts.

Example:

ResultSet rs1= statemnt1.executeQuery(QUERY));

20
SCOPE
CSI3018- Advanced Java

6. Processing the Result Set

 the queries using the executeQuery() method, the result will be stored in the ResultSet
object.
ResultSet rs1= statemnt1.executeQuery(QUERY));

 A ResultSet object points to the current row in the Resultset. To iterate the data in the
ResultSet object, call the next() method in a while loop.
 If there is no more record to read, it will return FALSE.

21
SCOPE
CSI3018- Advanced Java

8. Closing the Connection


Finally, we are done with manipulating data in DB. Now we can close the JDBC connection.
 We need to make sure that we have closed the resource after we have used it

conn.close();

22
SCOPE
CSI3018- Advanced Java

JDBC Program

import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");

Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo","root",“password");

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" ");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
23
SCOPE
CSI3018- Advanced Java

JDBC CRUD Application


CRUD – Create Retrieve Update Delete
Create Query
Execute the following SQL script inside MySQL Workbench:

create database SampleDB; Statement stmt = conn.createStatement();


stmt.execute("CREATE TABLE address_book (Last_Name char(50) default ''," +
use SampleDB; "First_Name char(50),Email char(50),Phone_Number char(50))")

CREATE TABLE `users` (


`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`user_id`)
);

Or if you are using MySQL Command Line Client program, save the above script into a file, let’s say,
SQLScript.sqland execute the following command:
24
source Path\To\The\Script\File\SQLScript.sql SCOPE
CSI3018- Advanced Java

JDBC CRUD Application


SELECT Query
String sql = "SELECT * FROM Users";

Statement statement = conn.createStatement();


ResultSet result = statement.executeQuery(sql);

int count = 0;

while (result.next()){
String name = result.getString(2);
String pass = result.getString(3);
String fullname = result.getString("fullname");
String email = result.getString("email");

String output = "User #%d: %s - %s - %s - %s";


System.out.println(String.format(output, ++count, name, pass, fullname, email));
} 25
SCOPE
CSI3018- Advanced Java

JDBC CRUD Application


INSERT Query
String sql = "INSERT INTO Users (username, password, fullname, email) VALUES (?, ?, ?, ?)";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "bill");
statement.setString(2, "secretpass");
statement.setString(3, "Bill Gates");
statement.setString(4, "bill.gates@microsoft.com");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}

26
SCOPE
CSI3018- Advanced Java

JDBC CRUD Application


UPDATE Query
String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "123456789");
statement.setString(2, "William Henry Bill Gates");
statement.setString(3, "bill.gates@microsoft.com");
statement.setString(4, "bill");

int rowsUpdated = statement.executeUpdate();


if (rowsUpdated > 0) {
System.out.println("An existing user was updated successfully!");
}

27
SCOPE
CSI3018- Advanced Java

JDBC CRUD Application


DELETE Query

String sql = "DELETE FROM Users WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "bill");

int rowsDeleted = statement.executeUpdate();


if (rowsDeleted > 0) {
System.out.println("A user was deleted successfully!");
}

28
SCOPE
CSI3018- Advanced Java

JDBC Batch Updates


 A JDBC batch update is a batch of updates grouped together, and sent to the
database in one batch, rather than sending the updates one by one.
 You can batch both SQL inserts, updates and deletes. It does not make sense
to batch select statements.
 DatabaseMetaData.supportsBatchUpdates() method to determine if the
target database supports batch update processing
 addBatch() - used to add individual statements to the batch
 executeBatch() - used to start the execution of all the statements grouped
together.

There are two ways to execute a JDBC batch update:


Using a Statement
Using a PreparedStatement
29
SCOPE
CSI3018- Advanced Java

Batch Updates using Statements


// 1. Create statement object
Statement stmt = conn.createStatement();
// 2. Set auto-commit to false
conn.setAutoCommit(false);
// 3. Create one more SQL statement
String q1 = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// 4. Add above SQL statement in the batch.
stmt.addBatch(q1);

// 5. Create one more SQL statement


String q2 = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// 6. Add above SQL statement in the batch.
stmt.addBatch(q2);

// 7. Create an int[] to hold returned values


int[] count = stmt.executeBatch();
//8. Explicitly commit statements to apply changes
conn.commit(); 30
SCOPE
CSI3018- Advanced Java

Batch Updates using Prepared Statements


// Create SQL statement
String q1 = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(?, ?, ?, ?)";
// Create PrepareStatement object
PreparedStatemen pstmt = conn.prepareStatement(q1);
//Set auto-commit to false
conn.setAutoCommit(false);
// Set the variables
pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Raj" );
pstmt.setString( 3, "Kumar" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch();

//Create an int[] to hold returned values


int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes


31
conn.commit(); SCOPE
CSI3018- Advanced Java

JDBC Transaction

 transactions are designed to preserve data integrity by grouping multiple


statements to be executed as a single unit
 In a transaction, either all of the statements are executed, or none of the
statements is executed.
 If any statement failed to execute, the whole transaction is aborted and the
database is rolled back to the previous state.

32
SCOPE
CSI3018- Advanced Java

JDBC Transaction Workflow


try {
// begin the transaction:
connection.setAutoCommit(false);
// execute statement #1
// execute statement #2
// ...
// commit the transaction
connection.commit();

} catch (SQLException ex) {


// abort the transaction
connection.rollback();

} finally {

// close statements

connection.setAutoCommit(true);
} 33
SCOPE
CSI3018- Advanced Java

JDBC Transaction Workflow

connection.setAutoCommit(false);
By default, a new connection is in auto-commit mode. each SQL statement is treated as a
transaction and is automatically committed right after it is executed. So we have to disable the auto
commit mode to enable two or more statements to be grouped into a transaction.

connection.commit();
all subsequent SQL statements are included in the current transaction, and they are committed as a
single unit until we call the method commit()

connection.rollback();
If any statement failed to execute, a SQLException is thrown, and in the catch block, we invoke the
method rollback() to abort the transaction
34
SCOPE
CSI3018- Advanced Java

Save points in Transaction

try { // execute statement #5


// ...
// begin the transaction: // commit the transaction
connection.setAutoCommit(false); connection.commit();
// execute statement #1
// execute statement #2 } catch (SQLException ex) {
// statements #1 & #2 are executed successfully // abort the transaction
till this point: connection.rollback();
Savepoint savepoint = connection.setSavepoint();
// execute statement #3 } finally {
// execute statement #4 // close statements
connection.setAutoCommit(true);
if (/* something wrong */) { }
// roll back the transaction to the savepoint:
connection.rollback(savepoint);
}
35
SCOPE
CSI3018- Advanced Java

Thank you

36
SCOPE

You might also like