0% found this document useful (0 votes)
8 views76 pages

Advance Java Notes

JDBC (Java Database Connectivity) is an API that facilitates communication between Java applications and databases by converting Java statements into database-understandable language and vice versa. It requires a driver software to translate Java into specific database languages and involves a five-step process to establish a connection, create statements, execute queries, and close connections. The document also outlines how to create a Maven project for managing employee data, including operations like saving, updating, deleting, and fetching employee records using a PostgreSQL database.
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)
8 views76 pages

Advance Java Notes

JDBC (Java Database Connectivity) is an API that facilitates communication between Java applications and databases by converting Java statements into database-understandable language and vice versa. It requires a driver software to translate Java into specific database languages and involves a five-step process to establish a connection, create statements, execute queries, and close connections. The document also outlines how to create a Maven project for managing employee data, including operations like saving, updating, deleting, and fetching employee records using a PostgreSQL database.
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

JDBC

JDBC (java to database connectivity)

• It is an API used to establish connection between java to database.

API (application programming interface)

• It is a software that helps two applications to communicate with each other.

How does JDBC helps to connect java to database(theory)?

• When we have both java application and database application, and we want those to
communicate with each other, but java does not understand SQL language and
database does not understand java language.
• Now we need one mechanism which takes java statements and converts it into
database understandable language, and to convert database response into java
understandable language, for that we have our JDBC API.
• Now JDBC API will take java statements and converts into database under-stable
language and sends the request, now database will understand it and does
respective work.
• When database will take the information, it gives to JDBC API and it will convert
particular database into java understandable language.
• So JDBC will act as interface between java to database.

Note:
• JDBC API will convert java language into database understandable language, but it never
converts java to particular database language.

For that we need driver software.

• JDBC API alone cannot convert java into particular database language; in order to do
it we need a driver software, which is provided by database vendors.
• Since it is a third-party application to use it, we need to integrate it, for that we need
to add the dependency.
Driver:

• It is a class which is present in [Link] package (since we are using mysql


database)
• We need this to convert database language into particular MySQL database
language.

5-Steps to achieve connection between java to database using JDBC:


[Link] (or) Register the driver
[Link] connection
[Link] statement
[Link] query
[Link] connection

[Link] (or) Register the driver

• To use Driver class, we need to bring that into our java memory.
• We can load our driver class into java memory in 2 ways, either we can load (or)
register but not both at a time.

a) Register Driver Class:


[Link] the object of driver class. [Driver driver= new Driver ();]

• import it from [Link] package.

Step2. Ask the DriverManager to register the driver.

• DriverManager is a class present in [Link] package.


• In this class we have a static method that is –registerDriver(Driver reference),
• which accept Driver object reference as a parameter.
So,
[[Link](driver);]

• pass the driver object reference to the particular method, then it is going to register
your driver class into java memory.
• As soon as we write that line ,it will throw checked
exception(ClassNotFoundException) handle it by using try and catch.
--------------------------------------------------------------------------------------------------------------------------
b) Loading the Driver:
For mysql
[[Link](“[Link]”);]
For postgre sql
[Link]("[Link]");

• Class is class present in [Link] package, in that class we have a static method called
as forName()
• which will accept a string argument, where we will pass a FullyQualifiedClassName of
the mysql Driver provided by database vendors.
• This method loads our driver class into memeory.
• Driver object creation and registerDriver() both throws checked exception
(SQLException) handle it by using try and catch.

--------------------------------------------------------------------------------------------------------------------------
[Link] connection
We create a connection between java to database by passing three things:
[Link]
[Link]
[Link]

url- “jdbc: mysql://localhost:3306/databaseName” username-“root “password-“root.


Connection
con=[Link]("jdbc:postgresql://localhost:5432/databaseName",
"postgres", "your_password");

• We have getConnection() which is public static method present in DriverManager


class,
• this method is used to build the connection between java to database.
Mainly we have 3 getconnection(), which is overloaded method:
[Link] (string url, String username ,String password) ;
[Link](String url);
[Link](properties file,String url);

[Link] (string url, String username, String password) ;

• Here we have a getConnection() method, which accept three string arguments,


where will pass url inorder to get database location and password and username to
unlock database.
[[Link](url,username,password);]

• This line will throw you the checked exception SQLException, handle it.
--------------------------------------------------------------------------------------------------------------------------
[Link] (String url)

• This method accepts single string where we will pass user,password,url in one string
String url-
“jdbc:mysql://localhost:3306/databasename?user=root&password=root”

[Link] (properties file,String url);


--------------------------------------------------------------------------------------------------------------------------

• These methods are the example for built-in overloaded methods.


• These methods will return the object of Connection type.
[Connection connection=[Link]();]

• Since connection is an interface we cannot able to create an object directly ,so we


have getConnection() method.
• Connection is an interface present in [Link] package
• connection objects gets created only if url,password,username are accurate ,if any
one is wrong the getconnection() not all create an object, instead it will throw you an
sqlExeception.

[Link] Statement:
We can create statement in 2 ways
[Link]
[Link]

[Link]
Statement statement = [Link]();]

• Statement is a interface present in [Link] package.


• We can get statement object by calling createStatement method.
• createStatement() throws SQLException.
• generally statement object used to execute static query.
[Link]

• PreapresStatement is an interface present in [Link] package.


• It is child of Statement interface.
• we can get the PreparedStatement object by calling prepareStatement().
• prepareStatement() method throws the SQLException.
• PreparedStatement generally used to execute the dynamic queries.
• it is used to execute parameterised query ,we use the delimeter(?)and pass the value
to it by using setter method, we prefer prepareStatement over an Statement to
execute any query dynamically.

[Link] Querry

• This step is important inorder to insert the query inside the database
Here we have three methods inorder to execute the querries:
[Link]():
[Link]():
[Link]():

[Link] ():

• Used to execute both select and non-select queries


• it returns Boolean value
• Returns true if query is successfully executed.
[Link] ():

• This method used to execute only non-select queries


• Return type of this method is int
• It will return the value that how many rows are affected.
[Link] ():

• This method is used to execute only select queries, where this method will return the
ResultSet object.

[Link] connection

• It is one of the important part in our JDBC, Because if we don’t close the connection
,it will leads the connection memory leakage.
• the safe pattern in java is to close connection always.

ResultSet:

• It is an interface, present in [Link] package


• It holds/store the set of data’s return by executeQuery()
• result set will act as cursor, where it will point above the table initially,And to make
cursor to point first row of the given table we will make
• use of next (), where this method helps us to move the cursor to nextline
next ():

• it is present inside ResultSet interface, where it has boolean return type.


• if there any row existed in the next position it will return true.
• if there is no existed in the next position, it will return us a false.

- To fecth the data from resultset we have getX(column index)


- this method will fetch the value from particular column based on its index.
- X—represents datatype of a data.
--------------------------------------------------------------------------------------------------------------------------
Batch Execution (or)Batch processing

• Whenever we have multiple queries which need to be executed in one call we are
going to make use of batch processing.
• In batch execution all queries combined together and executed at once.
• batch processing allows us to group related SQL statement into a batch and submit
them with one call to the database.
--------------------------------------------------------------------------------------------------------------------------

Advanatage: -
Make the execution performance fast.

• we use addBatch() to add multiple quarries.


• we call executeBatch() to execute ,the quarries into database.
• Both addBatch() and executeBatch() is present in PreparedStatement.
--------------------------------------------------------------------------------------------------------------------------

Create a new Maven project called jdbc-employee-db-project and add the dependency in
[Link]. Create a database called empdetails, and create a table called employee with the
following columns: empid, name, salary, phno (VARCHAR), email, address, companyName.

Create a class called EmployeeDetails and inputs has to be taken


from user(use scanner).
have swith case where
[Link]
[Link]
[Link] Name
[Link] Salary
[Link] phno
[Link] Email
[Link]
[Link]
[Link]

import [Link].*;

public class EmployeeDbPostgres {


public static void main(String[] args) {
try {
// 1. Load/Register the driver
[Link]("[Link]");

// 2. Create connection
Connection con = [Link](
"jdbc:postgresql://localhost:5432/empdetails", // DB name must exist
"postgres", // username
"yourpassword" // password
);

// 3. Establish statement
Statement stmt = [Link]();

// 4. Execute query (Create table)


String query = "CREATE TABLE IF NOT EXISTS employee (" +
"empid SERIAL PRIMARY KEY, " +
"name VARCHAR(100), " +
"salary DOUBLE PRECISION, " +
"phno VARCHAR(15), " +
"email VARCHAR(100), " +
"address VARCHAR(255), " +
"companyName VARCHAR(100))";
[Link](query);
[Link]("Table created successfully.");

// 5. Close connection
[Link]();
[Link]();

} catch (Exception e) {
[Link]();
}
}
}
package [Link];

import [Link].*;
import [Link];

public class EmployeeDetails {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

try {
// Step 1: Load PostgreSQL Driver
[Link]("[Link]");

// Step 2: Establish Connection (PostgreSQL)


Connection con = [Link](
"jdbc:postgresql://localhost:5432/empdetails", "postgres", "password");
// Replace "postgres", "password" with your PostgreSQL username & password

[Link]("✅ Connected to PostgreSQL Database!");

while (true) {
[Link]("\n--- Employee Menu ---");
[Link]("1. Save Employee");
[Link]("2. Update Employee");
[Link]("3. Delete Employee");
[Link]("4. Fetch All Employees");
[Link]("5. Fetch Employee By ID");
[Link]("6. Exit");
[Link]("Enter choice: ");
int choice = [Link]();

switch (choice) {
case 1: // Save Employee
[Link]("Enter EmpId: ");
int id = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Salary: ");
double salary = [Link]();
[Link]();
[Link]("Enter Phone: ");
String phno = [Link]();
[Link]("Enter Email: ");
String email = [Link]();
[Link]("Enter Address: ");
String address = [Link]();
[Link]("Enter Company Name: ");
String company = [Link]();

String insert = "INSERT INTO employee VALUES (?, ?, ?, ?, ?, ?, ?)";


PreparedStatement psInsert = [Link](insert);
[Link](1, id);
[Link](2, name);
[Link](3, salary);
[Link](4, phno);
[Link](5, email);
[Link](6, address);
[Link](7, company);
[Link]();

[Link]("✅ Employee Saved Successfully!");


break;

case 2: // Update Employee


[Link]("Enter EmpId to update: ");
int uid = [Link]();
[Link]("a. Update Name");
[Link]("b. Update Salary");
[Link]("c. Update Phone");
[Link]("d. Update Email");
[Link]("Choose option: ");
char opt = [Link]().charAt(0);
[Link]();

String updateQuery;
PreparedStatement psUpdate;

switch (opt) {
case 'a':
[Link]("Enter New Name: ");
String newName = [Link]();
updateQuery = "UPDATE employee SET name=? WHERE empid=?";
psUpdate = [Link](updateQuery);
[Link](1, newName);
[Link](2, uid);
[Link]();
[Link]("✅ Name Updated!");
break;
case 'b':
[Link]("Enter New Salary: ");
double newSal = [Link]();
updateQuery = "UPDATE employee SET salary=? WHERE empid=?";
psUpdate = [Link](updateQuery);
[Link](1, newSal);
[Link](2, uid);
[Link]();

[Link]("✅ Salary Updated!");


break;
case 'c':
[Link]("Enter New Phone: ");
String newPh = [Link]();
updateQuery = "UPDATE employee SET phno=? WHERE empid=?";
psUpdate = [Link](updateQuery);
[Link](1, newPh);
[Link](2, uid);
[Link]();

[Link]("✅ Phone Updated!");


break;
case 'd':
[Link]("Enter New Email: ");
String newEmail = [Link]();
updateQuery = "UPDATE employee SET email=? WHERE empid=?";
psUpdate = [Link](updateQuery);
[Link](1, newEmail);
[Link](2, uid);
[Link]();

[Link]("✅ Email Updated!");


break;
default:

[Link]("❌ Invalid Option!");


}
break;

case 3: // Delete Employee


[Link]("Enter EmpId to Delete: ");
int did = [Link]();
String delete = "DELETE FROM employee WHERE empid=?";
PreparedStatement psDelete = [Link](delete);
[Link](1, did);
int rows = [Link]();
if (rows > 0)

[Link]("✅ Employee Deleted!");


else

[Link]("❌ No Employee Found!");


break;

case 4: // Fetch All Employees


String fetchAll = "SELECT * FROM employee";
Statement stmt = [Link]();
ResultSet rs = [Link](fetchAll);
[Link]("\nEmpId | Name | Salary | Phone | Email | Address |
Company");
[Link]("---------------------------------------------------------------------");
while ([Link]()) {
[Link]([Link](1) + " | " +
[Link](2) + " | " +
[Link](3) + " | " +
[Link](4) + " | " +
[Link](5) + " | " +
[Link](6) + " | " +
[Link](7));
}
break;

case 5: // Fetch Employee By ID


[Link]("Enter EmpId: ");
int fid = [Link]();
String fetchById = "SELECT * FROM employee WHERE empid=?";
PreparedStatement psFetch = [Link](fetchById);
[Link](1, fid);
ResultSet rsId = [Link]();
if ([Link]()) {
[Link]("EmpId: " + [Link](1));
[Link]("Name: " + [Link](2));
[Link]("Salary: " + [Link](3));
[Link]("Phone: " + [Link](4));
[Link]("Email: " + [Link](5));
[Link]("Address: " + [Link](6));
[Link]("Company: " + [Link](7));
} else {

[Link]("❌ No Employee Found!");


}
break;
case 6: // Exit
[Link]();
[Link]();

[Link]("👋 Goodbye!");
return;

default:

[Link]("❌ Invalid Choice!");


}
}

} catch (Exception e) {
[Link]();
}
}
}
Servlet

• Servlet is technology which is used to develop web applications.


• Servlet is an API that provides many interfaces and classes.
• Servlet in java is a class that runs on web server.
• Servlet class will acquire property of server creating response and reading request
sent by client.
• All classes related to servlet present in [Link] package.

What is Server?

• Server is a computer that provides service to another computer.


• Server accepts the requests sent by the client, process the request and sends back
the response to the client.

What is Web-Application?
Any application that requires internet and run on server.

How to create Servlet class?


[Link] implementing Servlet interface
[Link] extending GenericServlet class
[Link] extending HttpServlet class

Servlet interface

• Servlet is an interface present in javax. servlet package.


• Servlet is an interface that must be implemented for creating any Servlet.
• Any class inheriting servlet interface has to provide implementation to all methods of
servlet interface.

Methods of Servlet interface are: -


1. init()
2. service()
3. destroy()
4. getServletConfig()
5. getServletInfo()
• init(): Initializes the servlet; called once when the servlet is first loaded.
• service(): Handles client requests (GET/POST); called for each request.
• destroy(): Cleans up resources before the servlet is destroyed.
• getServletConfig(): Returns servlet configuration information.
• getServletInfo(): Returns information about the servlet (like version, author).

Generally we do not prefer implementing Servlet interface for creating Servlet class,we go
for extending GenericServlet class.

GenericServlet class

• GenericServlet is a class present in [Link] package.


• It is a implementing class of Servlet interface.
• It provides implementation for all the methods of Servlet interface except one
method i.e. service() method which is kept [Link] this class is abstract class.
• If we are trying to create servlet class by extending GenericServlet,then it is
mandatory to override service() method.

--------------------------------------------------------------------------------------------------------------------------
How to create maven for servlet?

• File--New--Maven Project--next--search maven-archetype-webapp 1.4 version--next--


give package name and project name --finish.
• Type y in console -----project build success.

Add dependency
Browser--maven repository--search Servlet api 4.0.1--copy and paste it in [Link] between
dependencies tag

Right click on project-- run as--run on server.


------------------------------------------------------------------------------

Creating servlet class using Servlet interface


In src/main/java create package and class.

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FirstServlet implements Servlet


{

@Override
public void init(ServletConfig config) throws ServletException {
}

@Override
public ServletConfig getServletConfig() {
return null;
}

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
[Link]("hii my name is simran");
}

@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public void destroy() {
// TODO Auto-generated method stub

In src--main--WebApp--WEB-INf we have [Link] ,


Where we need to register our servlet class and provide mapping

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/message</url-pattern>
</servlet-mapping>
</web-app>

Right click on project-- run as--run on server.


And give url as message to trigger the servlet.
--------------------------------------------------------------

Creating servlet class using GenericServlet class


In src/main/java create package and class.

Extend to GenericServlet class and override service() method

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Sample extends GenericServlet


{

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
[Link]("Hello welcome");
}

}
In src--main--WebApp--WEB-INf we have [Link] ,
Where we need to register our servlet class and provide mapping

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>allen</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>allen</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>

</web-app>

Right click on project-- run as--run on server.


And give url as apple to trigger the servlet.
--------------------------------------------------------------------
service() method:

• Service method is an abstract method which must be implemented.


• The service method accepts the request and provides service for each request sent
by the client.
• The service method is like a main method which is expected to perform the actual
task.
• The service method accepts 2 parameters, ServletRequest object, ServletResponse
object,
• ServletRequest object-It stores the data sent by the client through the request.
• ServletResponse object-It stores the response generated by the servlet that needs to
be sent to the client.

Note:
ServletRequest and ServletResponse are interface.

--------------------------------------------------------------------------------------------------------------------------
To print some message in browser we need to use PrintWriter

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Sample extends GenericServlet


{

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>Welcome to my page</h1>");
[Link]("</body></html>");

}
In src--main--WebApp--WEB-INf we have [Link] ,
Where we need to register our servlet class and provide mapping

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>allen</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>allen</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>

</web-app>

Right click on project-- run as--run on server.


And give url as apple to trigger the servlet.

--------------------------------------------------------------------------------------------------------------------------
Printwriter

• Printwriter is a class which is defined in [Link] package.


• Printwriter class is used to display the data on the webpage through a Java program.
• It consists of method print ("html code") for printing the data on the webpage.

--------------------------------------------------------------------------------------------------------------------------
Form creation and triggering servlet class via form.

In src-main-webapp,
Right click on webapp-new -html file-give fileName with .html extension(Ex:[Link])

Create a form:
<body>
<form action="apple">
Name:<input type="text" name="username">
<br><br>
Age:<input type="text" name="userage">
<br><br>
<input type="submit" value="submit">

</form>
</body>

Create a servlet class:

public class Sample extends GenericServlet


{

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>Welcome to my page</h1>");
[Link]("</body></html>");
}

In src--main--WebApp--WEB-INf we have [Link] ,


Where we need to register our servlet class and provide mapping

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>allen</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>allen</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>

</web-app>

Right click on [Link]-- run as--run on server.


fill the info in form ----click on submit--respective servlet will be triggered.
--------------------------------------------------------------------------------------------------------------------------
Read form data into servlet class (Using GenericServlet):

With help of getParameter() method we can read form data.


It is present in request object.
Its retuirn type is String.

• It accepts a String formal argument,where we need to give same value given in


repective name attribute in form.
In src-main-webapp,
Right click on webapp-new -html file-give fileName with .html extension(Ex:[Link])

Create a form:
<body>
<form action="apple">
Name:<input type="text" name="username">
<br><br>
Age:<input type="text" name="userage">
<br><br>
<input type="submit" value="submit">

</form>
</body>

Create a servlet class:

public class Sample extends GenericServlet


{

@Override
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
//read form data
String name=[Link]("username");
String age=[Link]("userage");

PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>User name is :"+name+"</h1>");
[Link]("<h1>User age is :"+age+"</h1>");
[Link]("</body></html>");

In src--main--WebApp--WEB-INf we have [Link] ,


Where we need to register our servlet class and provide mapping

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>allen</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>allen</servlet-name>
<url-pattern>/apple</url-pattern>
</servlet-mapping>

</web-app>

Right click on [Link]-- run as--run on server.


fill the info in form ----click on submit--respective servlet will be triggered.
--------------------------------------------------------------------------------------------------------------------------
HttpServlet:

• The HttpServlet is an abstract class present in [Link] package


• In HttpServlet there are no abstract method but still they have made HttpServlet
class
• as an abstract class because ,to avoid unwanted object creation directly.
• To create servlet class we were generally recommend to extend HttpServlet class.
• HttpServlet class is a subclass of GenericServlet where service method is overriden.

For handling request sent by the client HttpServlet class provides following methods:

[Link](ServletRequest req,ServletResponse res)


[Link](HttpServletRequest req, HttpServletResponse res)
[Link](HttpServletRequest req, HttpServletResponse res)
[Link](HttpServletRequest req,HttpServletResponse res)
[Link](HttpServletRequest req,HttpServletResponse res)

This method accepts 2 parameters:

• [Link] object-it stores the data sent by the client through the request.
• [Link] object-it stores the response of the servlet that needs to be
sent to the client.

--------------------------------------------------------------------------------------------------------------------------

Reading form data using HttpServlet doGet() method.

<body>
<form action="mango" >
Name:<input type="text" name="user-name"><br><br>
Age:<input type="text" name="user-age"><br><br>
Email:<input type="text" name="user-email"><br><br>
Password:<input type="text" name="user-password"><br><br>
<input type="submit" value="submit">
</form>
</body>

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class UserRegister extends HttpServlet


{
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException
{
String name=[Link]("user-name");
String age=[Link]("user-age");
String email=[Link]("user-email");
String password=[Link]("user-password");

PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>User Information</h1>");
[Link]("<h3> Name is:"+name+"</h3>");
[Link]("<h3> Age is:"+age+"</h3>");
[Link]("<h3> Email is:"+email+"</h3>");
[Link]("<h3> Password is:"+password+"</h3>");
[Link]("</body></html>");

}
}

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>flower</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>flower</servlet-name>
<url-pattern>/rose</url-pattern>
</servlet-mapping>

</web-app>
--------------------------------------------------------------------------------------------------------------------------
Reading form data using HttpServlet doPost() method.
<body>
<form action="mango" method="post">
Name:<input type="text" name="user-name"><br><br>
Age:<input type="text" name="user-age"><br><br>
Email:<input type="text" name="user-email"><br><br>
Password:<input type="text" name="user-password"><br><br>
<input type="submit" value="submit">
</form>
</body>

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class UsingDoPostMethod extends HttpServlet{

@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,
IOException
{
String name=[Link]("user-name");
String age=[Link]("user-age");
String email=[Link]("user-email");
String password=[Link]("user-password");

PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>User Information</h1>");
[Link]("<h3> Name is:"+name+"</h3>");
[Link]("<h3> Age is:"+age+"</h3>");
[Link]("<h3> Email is:"+email+"</h3>");
[Link]("<h3> Password is:"+password+"</h3>");
[Link]("</body></html>");

}
}

<web-app>
<servlet>
<servlet-name>fruit</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>fruit</servlet-name>
<url-pattern>/mango</url-pattern>
</servlet-mapping>
</web-app>
--------------------------------------------------------------------------------------------------------------------------

RequestDispatcher

RD is an interface present in [Link] package.


Use: To dispatch the request from one servlet to another servlet or one servlet to another
jsp/html page or from or html to another html page.

forward() :it forwards the request from one servlet to another resource(servlet,html,jsp) on
the server.

<body>
<form action="calculate">
Height:<input type="text" name="height"><br><br>
Weight:<input type="text" name="weight"><br><br>
<input type="submit" value="Calculate">
</form>

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CalculateBMI extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String height=[Link]("height");
String weight=[Link]("weight");
//Here height and weight are in the form of string,hence we to
//parse it to double data
double h=[Link](height);
double w=[Link](weight);

double value=w/(h*h);//kg/m2
/*Now i dont need these things to be printed in same page,
* ill have it in different page ....so that i need to forward that
* request.
* */
/*
* in order to acess the attributes in different class ,we need to set attribute
* in key and value format.
* */
[Link]("height1", h);
[Link]("weight1", w);
[Link]("value1", value);

RequestDispatcher dispatcher=[Link]("result");
[Link](req, resp);
}
}

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class BMIResult extends HttpServlet


{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {

double h=(Double)[Link]("height1");//return in form of Object


double w=(Double)[Link]("weight1");
double value=(Double)[Link]("value1");

String result="";

if(value<18)
result="Under weight";
else if(value>=18 && value<25)
result="Normal";
else if(value>=25 && value<30)
result="Over weight";
else
result="Obese";

PrintWriter p=[Link]();
[Link]("<html><body>");
[Link]("<h1>Height is :"+h+"</h1>");
[Link]("<h1>Weight is :"+w+"</h1>");
[Link]("<h1>Value is :"+value+"</h1>");
[Link]("<h1>Result is :"+result+"</h1>");
[Link]("</body></html>");

}
}

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>page-a</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>page-a</servlet-name>
<url-pattern>/calculate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>page-b</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>page-b</servlet-name>
<url-pattern>/result</url-pattern>
</servlet-mapping>

</web-app>

--------------------------------------------------------------------------------------------------------------------------
include()-it includes the content of a servlet in another resource.

<body>
<form action="login">
UserName:<input type="text" name="username"><br><br>
Password:<input type="text" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>

package [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Validation extends HttpServlet


{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String username=[Link]("username");
String password=[Link]("password");

PrintWriter p=[Link]();

//validate
if([Link]("admin") &&
[Link]("admin")) {
[Link]("<html><body>");
[Link]("<h1>Login success</h1>");
[Link]("</body></html>");
}
else {
[Link]("<html><body>");
[Link]("<h1>Login failure</h1>");
[Link]("<h2>Please enter correct details</h2>");
[Link]("</body></html>");
RequestDispatcher
dispatcher=[Link]("[Link]");
[Link](req, resp);
}

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>login</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
--------------------------------------------------------------------------------------------------------------------------

• sendRedirect() method-It is defined in HttpServletResponse interface,that means it


can be accessed only in HttpServlet class.
• This method sends the response to another resource, inside or outside the server.
• it accepts url to which the response has to be redirected..
<body>
<form action="information">
Select any one:
<select name="Fruits-type">
<option>Apple</option>
<option>Mango</option>
<option>Grapes</option>
<option>chicoo</option>
<option>orange</option>
</select><br><br>
<input type="submit" value="search">

</form>
</body>

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

/*
* sendRedirect()----present in response object
* It is used to redirect the request to different external resource/page/
* application/third party page.
*
* */
public class Information extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String choice=[Link]("Fruits-type");

if([Link]("Apple")) {
//apple info
[Link]("[Link]
}
else if([Link]("Mango")) {
//mango info
[Link]("[Link]
}
else if([Link]("Grapes")) {
//grapes info
[Link]("[Link]
}
else {
[Link]("[Link]
}

}
}

<web-app>
<servlet>
<servlet-name>info</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>info</servlet-name>
<url-pattern>/information</url-pattern>
</servlet-mapping>

</web-app>
--------------------------------------------------------------------------------------------------------------------------
How does servlet works:

• Servlet is a small piece of program that run on the server, now with any device we
send the request to the server
• Then server will sends the request to the servlet Container ,where servlet container
will process the request and it going to trigger proper servlet class present inside the
server,and inside servlet classes we will
• be having service() where that method is invoked and accept the request and sends
back the response.
• Servlet container(it will process the url of request and url the has been given to
servlet class)
--------------------------------------------------------------------------------------------------------------------------
SessionManagement

• It refers to the process of maintaining stateful information about a user’s interaction


with a web application across multiple request
Since the http request is stateless, meaning each request from a client to
a server is independent.

• when we send the request to server ,it will considered each request as a new request
,because http protocal are stateless,so server cannot remember details about us,
So everytime when we want to open an web application ,it will ask the authentication , so
we must manage the status (or) session , so that our server will see the status and provides
the response who already logged in
To manage the session, we have sessionmanagement

Inorder to manage the session we have 4 techniques


[Link]
[Link] form field
[Link] re-writting
[Link]
--------------------------------------------------------------
Cookies

• It is a class in java servlet present in [Link] package,which is


used to manage the session.
• Cookie is an object which can store a small piece of information.
• Cookies will store the values in the form of key and value pair
• For one application we can create multiple cookies

--------------------------------------------------------------------------------------------------------------------------

Program to create a cookie,fetch the cookie abd destroy the cookie

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/*
* Program to create the cookie
* */
public class PageA extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
Cookie cookie=new Cookie("name", "allen");
[Link](cookie);
[Link]("Cookie created");
}
}
/*
* Trigger this servlet
* In browser right click -----click on inspect---open application
*
* youll get cookie option
* */

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/*
* Program to fetch the cookie
* */
public class PageB extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
Cookie [] c = [Link]();

for(Cookie cookie:c) {
[Link]([Link]());
[Link]([Link]());
}

}
}

package [Link];

import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/*
* Program to destroy the cookie
* */
public class PageC extends HttpServlet

{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
Cookie [] c=[Link]();

for (Cookie cookie : c) {

String name=[Link]();

if([Link]("pi")) {
[Link](0);
[Link](cookie);
}

}
}
}

<!DOCTYPE web-app PUBLIC


"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link] >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>cookie</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>cookie</servlet-name>
<url-pattern>/pagea</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>read</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>read</servlet-name>
<url-pattern>/pageb</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>destroy</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>destroy</servlet-name>
<url-pattern>/pagec</url-pattern>
</servlet-mapping>
</web-app>
--------------------------------------------------------------------------------------------------------------------------

Servlet life cycle


The servlet lifecycle is controlled and takencare by our servlet container.

1. Loading servlet class


Class loader is responsible to load the servlet classes into memory
class loaders loads the servlet classes into the memory
when it receive first request ,for second time if we requested also it
wont be load the object into memory again.

[Link] of servlet classes


servlet container will create an object of servlet class ,inorder to
access the non static method inside it
the object of servlet class is going to create only once in the entire
lifecycle ,because servlet container will instantiate an object only once.

[Link]
Our servlet container will initialize the values present inside an
servlet classes by using init()
This also happen only once for entire life cycle.

[Link] service()
This step is much important, where this method is going to
invoked for each and every request that we make.
[Link] servlet class
Servlet container will destroys the servlet class by using destroy()
And this is gonna happen only once for whole servlet lifecycle.

1. Create a Servlet Web App Maven project named employee-servlet-jdbc.


2. Add Servlet and MySQL dependencies in [Link].
3. Create a database called employee-servlet-jdbc.
4. Create a table called employee with the following columns: id, name, email,
password, salary.
5. Create a [Link] form and accept inputs: id, name, email, password, salary.
6. Create a Servlet class Register, read data from [Link], and store it in the
database using PreparedStatement.
7. Create a [Link] form to accept email and password.
8. Create a Servlet class Login, read data from the form, and check if the data is present
in the database.
9. If the data is found, display "Login Success"; otherwise, display "Login Failure" and
show the same form again.
10. Make use of HttpSession for session management.
11. Create another Servlet class Display, fetch all data from the table, and forward it to
[Link].
12. In [Link], retrieve the data and display it in table format.

1. Create a Servlet web app Maven project with group ID [Link] and
artifact ID employee-servlet-jdbc.
2. Add Servlet and MySQL dependencies in [Link].
3. Create a database called employee-servlet-jdbc.
4. Create a table called employee with the following columns: id, name, email,
password, salary (Double).
5. Create a [Link] form to accept: id, name, email, password, and salary.

6. Create a Servlet class Register and map its URL to /register.


Also, set the same URL in the action attribute of the form in [Link].
7. Override the doGet() method.
8. In the doGet() method, read the data from [Link] and store it in variables.
9. In the same method, write the 5 steps of JDBC to store the data in the employee
table using PreparedStatement.

10. Create a [Link] form to accept email and password.


11. Create a Servlet class Login, read data from the form, and check whether the data is
stored in the database or not.
12. If the data is present, display Login Success, and store email and password in
HttpSession.
13. If the data is not present, display Login Failure and show the same form again.

14. Create another Servlet class called Display.


15. Fetch all the data from the table and store the result in a ResultSet object.
16. Set the ResultSet object as a request attribute using setAttribute and forward the
request to [Link].
17. In [Link], use JSP tags to get the ResultSet object using the key and
store it in a reference variable.
Hibernate
Framework:
It is collection of classes of predefined code that allows developers to add them to their own
code to solve a problem.
It provides required functionality to build and deploy an application.
Ex: Hibernate & Spring.

Hibernate
It is a java framework.
It was started in 2001 by Galvin King.
It was built as an alternate for JDBC
It simplifies the development of java applications to interact with the database.
It is an open source, ORM (Object Relational Mapping) tool.
Hibernate framework implements Java Persistence Api (JPA) to communicate with the
database.

Hibernate Over JDBC

• Hibernate provides inbuilt methods for performing the database operations which
makes the application development easy and fast.
• Hibernate never throws Checked [Link], hibernate handles all checked
exception by itself
o JDBC throws checked exception.
• Hibernate does not create a connection object each time. It maintains a connection
pool(Contain objects of Connection) where in JDBC for each connection requested
each time a new Connection Object will be created.
• Hibernate framework provides facility to create tables of the database automatically.
So there is no need to create tables in the database manually, but in JDBC table
should be created manually.
• Hibernate provides the facility for generating integer id values automatically.
• Fetching data from multiple tables is easy in hibernate framework, not in JDBC.
• Hibernate is Database Independent where as JDBC is Database Dependent.
o Hibernate make use of HQL.
o HQL(Hibernate Query Language) is the object-oriented version of SQL.
• It generates the database independent queries. So, no need to write database
specific queries.
• The performance of hibernate is fast compare to JDBC due to caching mechanism(1st
level and 2nd level caching).

In hibernate how data will be stored?


In the form of an object, where as in JDBC data will be stored in form of values.
In hibernate : java----Objects----Database
In JDBC : java-----Objects----Values----Database.

ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
It internally uses JDBC API to interact with database.

Java Application-----Object-----ORM tool (Hibernate)-------JDBC API------Database.

In hibernate, the class is connected to table and the variable are connected to columns of
table and each object is placed in form of rows.

Steps to create Hibernate Project:-


[Link] simple maven project
[Link] [Link] add 2 dependency i.e hibernate core and mysql dependency.
[Link] database in mysql workbench.
[Link] main/src/resources create a folder called META-INF
inside this folder create file called [Link].
[Link] [Link] file we have to set database name,user and password.

Entity class
a Java class whose objects (instances) are mapped to a table in the database.
Rules to create an Entity class

• class should be annotated with @Entity


• entity class must have one primary key (id) to a row for easy identification of objects
and annotated with @Id
• class must be public non abstract class.
• class should have public zero parameterized constructor or public default
constructor.
• for every variable of entity class there should be public getter and setter methods.

JPA (Java Persistence API)


stands for Java Persistence API.

• JPA is a Java specification which provides certain functionalities to Hibernate


framework.
• JPA defines the management relational data in the Java application.
• JPA defines how to persist data in Java application.
• The [Link] package contains all the JPA classes and interfaces.

Components of Hibernate JPA framework.


Persistence.

• The persistence class loads the startup instruction of the application.


• It consists of method called create entity manager factory which accepts persistent
unit name as a input
• once the persistence file is [Link] method return an object of
EntityManagerFactory.
EntityManagerFactory.

• It is an interface used to interact with entity managers for the given persistence unit.
An entity manager factory type object is created for a specific database.
• It consists of method called create entity manager which creates and returns an
object of entity manager type.
EntityManager.
It is an interface used to allow the application to manage and search for the object in the
database.
The Entity manager interface manages the lifecycle of entity.
Entity Manager interface consists of the following methods persist(), remove(),merge(),
find(), createQuery(), getTransaction().
• persist(object)-- It is used to insert an object into the database.
• remove(object)--- It is used to delete an object from the database.
• merge(object)--- It is used to update the states of the given object into the existing
object.
• find(entity [Link],primarykey values)-- it is used to search for an object
based on primary Key value
• createQuery(string hql/jpql query)----It is used to create an object of query type for
executing a HQL or JPQL query
• getTransaction()--It is used to create and return an object of entity transaction type.

EntityTransaction
It is an interface which is used to control the transaction on the entity manager.
It consists of the following methods.

• begin()----- it is used to start the transaction.


• commit()---- ends the current transaction and saves the changes in database.

Query:
It is an interface and the object of Query Interface type is used for storing HQL or JPQL
Query.
The object of Query interface can be obtained by calling the createQuery() method present
in
EntityManager Interface.
The object of Query interface can be used for executing HQL/JPQL Queries.
It has method called---

• getResultList() : It is used to execute a select query that return the result as list(from
[Link] package).

JPQL:

• JPQL stands for Java Persistence Query Language.


• It is a Query Language defined in JPA specifications.
• JPQL is an object oriented version of SQL.
• It is a used to create Queries to be executed against Relational Database.
• It is a database independent query language.
• EntityManager createQuery() method supports HQL/JPQL Queries.
---------------------------------------------------------------------------------------------------------------------
Mapping

• It is one of the key features in hibernate.


• It is used to establish connection between 2 tables.
• In hibernate we can achieve mapping in four ways.
They are
1. one to one mapping,
2. one to many mapping,
3. many to one mapping,
4. many to many mapping.

One to one mapping ---------

• is nothing but one single entity is associated with single instance of another entity.
• We can achieve one to one mapping with the help of annotation called @OneToOne

One too many ----------


the one row in a table is mapped with multiple rows in another table is called as one to
many mapping.
We can achieve one to many mapping with the help of annotation called @OneToMany

Many to one mapping ----------


many rows in the table is mapped with single row in another table.
We can achieve this using annotation @ManyToOne

many to many mapping ------------


many rows in a table mapped with multiple rows in another table.
This is achieved using annotation @ManyToMany

Mapping can done in 2 ways


[Link] Mapping ---Assume Bank has a Account
Using Bank Object you can fetch all datails of Account,But using Account object you
cannot fetch details of [Link] this case we call it as Unidirectional Mapping/Relationship.

[Link] Mapping--From bank Object we can fetch all details of Account.


And from Account Object we can fetch all details of [Link] this case we call it as
Birectional
Mapping/Relationship.

Annotations
They are piece of text which provides some information to the compiler and JVM.
It is used to give information about class, methods, interfaces and variables.

@Entity

• It is used on class.
• It specifies that class can be mapped to the table into the database.
• It specifies that class is an entity class.

@Id

• It is used on Variable.
• It specifies the below variable is the primary key for the current entity.

@GeneratedValue

• This annotation is used along with @Id annotation to automatically generate unique
values for primary key column within the database table.
• When we apply this annotation to primary key ,it will interact with hibernate to
automatically generate unique value for that field during the process of persisting the
entity into the database.
• It provides different strategies to generate such as AUTO,IDENTITY,TABLE,SEQUENCE.
For MySql database we prefer IDENTITY.

@Table
• It is used on entity class.
• This annotation allows an attribute called name,this is used to override the
tablename in the database. Ex @Table(name="my_tableName")

@Column

• It is used on variables.
• This is used to modify the columns in the database table.
• It allows following properties
1. name--we can change the name of the column in the databse Table.
2. length--we can change length of column mostly used in String.
3. nullable--used to specify whether null values are allowed or [Link] value is
true i.e. null values are allowed by default.
a. If null should be avoided then set nullable=false.
4. unique--It is to specify whether duplicate values are allowed or not.
a. The default value for unique is false i.e duplicates are allowed by default.
b. To only allow unique values set unique=true.

Caching

• Caching is a part of temporary memory.


• It is a mechanism used to enhance the performance of the application.
• It is a temporary memory that lies between application and the database.
• It enhances the performance of the application by reducing the number of requests
to be sent to the database.
Hibernate use two level of cache,
1. first level cache
2. second level cache

1. first level cash


• Implicitly Hibernate is enabled with first level cache.
• First level Cache is the entity manager level cache or session level cache. (one per
one entity manager)
• It is a mandatory cache through which every request must pass.
• By default, first level cash will be enabled in the Hibernate framework.
• First level cache is used for minimising the database interaction.

2. Second level cash


• If we are dealing with only single session(single entity manager) then first level cash
is the best suitable. (one per one entityManaherFactory).
• If we are having multiple session(multiple entity manager) then first ever cache is of
no use therefore we go for second level cash.
• Second level cash is a factory level cash and it is available across all the sessions
within the factory.
• It is not enabled by default since it is not available by default.
• It is the programmer responsibility to enable the second level cache.
• Hence the programmer decides with strategy needs to be enabled and also
programmer needs to configure the cache property in the [Link] file.

<property name="[Link].use_second_level_cache" value="true"></property>


<property name="[Link].factory_class"
value="[Link]"></property>

Use @Cacheable for entity class below @Entity

@JoinColumn
--used to merge the columns in database.
when we use @JoinColumn in opposit class we have to use mappedby="ref" mandatorily.

[Link]

• It is a standard configuration file.


• It should be included in META INF folder inside the resources folder.
• The [Link] file must define our persistence unit name. This file can be
accessed only by using the persistence unit name.
• [Link] file is used to configure the Hibernate application and to provide
database details.
• It is also used to configure the cache memory property for enhancing the
performance of its application.

The persistence file contains the following tags.d

<persistence-unit name="vikas">
It is used to define a unique name using which the [Link] file can be accessed.
<provider>[Link]</provider>
It defines implementation of JPA.

<property name="[Link]" value="[Link]" />


<property name="[Link]" value="jdbc:mysql://localhost:3306/demo" />
<property name="[Link]" value="root" />
<property name="[Link]" value="root" />

• This property specifies the driver which needs to be loaded and registered.
• It is used to specify the database url and database name.
• This used to specify the username and password of the database.

<property name="hibernate.show_sql" value="true" />

• This user to display all the queries executed internally on the control. If you do not
want to execute the SQL enquiries to be displayed then make the values as false.

<property name="[Link]" value="update" />


This property is responsible for automatic table creation. If this property is removed from
the [Link] file, table will not be created automatically. In such case we will have to
create the table manually.
value="create"----each time new table will be [Link] there is any old data with same
name,it will be deleted.
value="update"---if table is not present, then it will create the table and update the values.

if table is already present then it will only update the table.

<property name="[Link]" value="[Link].MySQL8Dialect"/>


It specifies to java application to tell which database we are [Link] that hibernate can
generate appropriate type of sql queries.

Hibernate life cycle


Transient State-is the initial state of an [Link] we create an object for entity class the
object enters into transient state, which means entity object is existing but there is no
connection made to entity object and row in a state. If any changes is done on entity object
it will not reflect in table.
Persistent State-Once we try to persist or update data into database ,the object enters
transient to persistent state, which means here object and row are [Link] any changes
is done on entity object it will reflect in table.
Detached State-Once we close the connection or call remove() on that time object enters
persistent to detached state, which means here connection between object and row is
removed.

Objects not used is taken by garbage collector.


After detached if you call merge() it will reenter to persistent state.

Task:1
Create a maven webapp project .
Add servlet,hibernate and mysql dependencies.
Create a html page form which can accept Car info like carname,carprice,carcolor and also
engine info like enginetype and enginecc.
Create 2 entity class Called Car and Engine and have datamembers for car as
carid,carname,carprice,carcolor
datamembers for engine as engineid,enginetype and enginecc.
Generate id for both automatically,make the datamembers as private and generate getter
and setter methods.
Achieve One To One Mapping Bidirectional between Car and Engine and use join column
annotation.
Create a servlet class which will read all data from html page and store it in [Link]
hibernate store all data
into database by creating objects of Car and Engine and set the respective values.
When you click on submit of html page ,this servlet class has to be triggered and data must
be stored in database.
(here no main method is used everything written in doPost() method.)
Create another servlet class and fetch all details of car and engine and send it to jsp page.
Create a jsp page which will display all info Car and Engine.

Create a form which accepts id of car and when you click on submit it has to display only
that car info along with its engine info.

-------------------------------------------------------------------------------------------------------------------
Task:2
Create a maven webapp project (servlets project).
Add servlet,hibernate and mysql dependencies.
if src/main/resources is not present then create it as below:
to create src/main/resources folder---select JavaResources-right click on it-new-select source
folder
browse your project--give name as src/main/resources--click on finish
now add META-INF and [Link]
Create a html page form which can accept employee info like name,age,salary
,email,password
and also address info like houseNumber,street,pincode,state,country.
Create a package [Link] under src/main/java under which
Create 2 entity class Called Employee and Address and have datamembers for
Employee as empid,name,age,salary,email,password
datamembers for Address as addresssid,houseNumber,street,pincode,state,country.
Generate id for both automatically,
make the datamembers as private and generate getter and setter methods.
Achieve One To One Mapping between Employee and Address

Create a servlet class which will read all data from html page,create Object of entity class set
the values and.
Using hibernate store all data
into database,

by creating objects of Person and Address and set the respective values.
When you click on submit of html page ,this servlet class has to be triggered and
data must be stored in database.
(here no main method is used everything written in doGet() method.)

Create another servlet class and fetch all details of Employee and Address and send it to jsp
page.
Create a jsp page which will display all info of Employee and Address.

Create a form [Link] which accepts email and password.


Create a servlet class [Link] in which read data from form and
validate if it is present in db or not
if present display Login Success message with employee name
if not present display Login failure message and diplay same login form again.
----------------------------------------------------------------------------------------------------------------------
Create a maven webapp project (servlet project).
Add servlet,hibernate,lombok and mysql dependencies.
to create src/main/resources folder---select JavaResources-right click on it-new-select source
folder
browse your project--give name as src/main/resources--click on finish
now add META-INF and [Link]

Create 3 packages under src/main/java


[Link]
[Link]
[Link]

Under [Link] create 2 entity classes Employee ,Task and one Enum Status.
write code as below
@Entity
@Getter
@Setter
public class Employee {
@Id
@GeneratedValue(strategy = [Link])
private int id;
private String name;
private int age;
private double salary;
private String email;
private String password;
private long phoneNumber;
private String role;
@OneToMany
private List<Task> tasks;
}
@Entity
@Getter
@Setter
public class Task {
@Id
private int taskId;
private String taskName;
private int duration;
private Status taskStatus;
}
public enum Status {
ASSIGNED,COMPLETED
}

Create [Link] page and use 2 anchor tags as Register and Login

Create a form in [Link] and accept


name,email,password,salary,phonenumber,gender.
AutoGenerate Id
Create a servlet class in [Link] package RegisterManager and read data from [Link]
,set role as manager
explicitly and store it in database

---------------------------------------------------------------------
State Description
New (Transient) The entity is not in the database and not managed by EntityManager.
Managed (Persistent) The entity is associated with an active EntityManager; changes are
automatically tracked and synchronized to the database.
Detached The entity was managed, but now the EntityManager is closed or the
transaction ended.
Removed The entity is scheduled for deletion from the database upon transaction
commit.

New (Transient)
Person p = new Person();
[Link]("John"); // not yet persisted, no DB row
------------------------------
2. Managed (Persistent)

EntityManager em = [Link]();
[Link]().begin();
[Link](p); // Now managed
[Link]("Jack"); // Will be auto-updated in DB

[Link]().commit();
[Link]();
------------------------------
3. Detached

[Link](); // now p is detached

[Link]("Mark"); // Will NOT be reflected in DB

EntityManager em2 = [Link]();


[Link]().begin();
[Link](p); // Re-attaches and becomes managed again
[Link]().commit();
------------------------------------
4. Removed

EntityManager em = [Link]();
[Link]().begin();

Person p = [Link]([Link], 1);


[Link](p); // scheduled for deletion

[Link]().commit(); // record deleted


[Link]();
--------------------------------------
JPA Entity Life Cycle Flow (Text Diagram)
NEW (Transient)
↓ persist()
MANAGED (Persistent)
↓ detach() or close()
DETACHED
↑ merge()
MANAGED
↓ remove()
REMOVED
---------------------------------------------

Strategy Description Underlying Mechanism

AUTO Hibernate picks the strategy based on the Could use IDENTITY,
database dialect. SEQUENCE, or TABLE.

IDENTITY Database auto-increments the ID (like Primary key generated by


MySQL AUTO_INCREMENT). DB after insert.

SEQUENCE Uses a database sequence object (like in Pre-fetches next value


Oracle, PostgreSQL). using nextval.

TABLE Uses a separate table to generate unique Simulates sequence using


IDs. a custom table.

UUID Generates 128-bit UUIDs. Doesn't need a database


(Hibernate sequence or table.
only)

1. AUTO (default)

@Id
@GeneratedValue(strategy = [Link])
private Long id;
Best when you want Hibernate to decide based on DB.
Not portable across all DBs unless configured carefully.

🔹 2. IDENTITY

@Id
@GeneratedValue(strategy = [Link])
private Long id;
Ideal for MySQL, SQL Server.

Value is auto-incremented by the DB.

🔹 3. SEQUENCE

@Id
@GeneratedValue(strategy = [Link], generator = "emp_seq")
@SequenceGenerator(name = "emp_seq", sequenceName = "employee_sequence",
allocationSize = 1)
private Long id;
Best for Oracle, PostgreSQL.

Requires a sequence in DB.

More efficient for batch inserts (when allocationSize > 1).

🔹 4. TABLE

@Id
@GeneratedValue(strategy = [Link], generator = "tab_gen")
@TableGenerator(name = "tab_gen", table = "id_generator", pkColumnName =
"gen_name", valueColumnName = "gen_val", pkColumnValue = "emp_id", allocationSize = 1)
private Long id;
Uses a separate table to track primary key values.

Slower but works on any database.

🔹 5. UUID (Hibernate-specific)

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
Good for distributed systems.

Generates globally unique IDs.

Summary

Strategy DB Support Use Case Notes

AUTO All Let Hibernate decide Not always predictable

IDENTITY MySQL, SQL Auto-increment No batch insert optimization


Server columns

SEQUENCE Oracle, Sequence-based IDs Best for performance


PostgreSQL

TABLE All Portable but slow Used when no sequence


support

UUID All Distributed, global IDs Hibernate only


:-Spring Boot DevTools
Spring Boot DevTools is a developer-friendly tool that improves the development
experience by automatically restarting, reloading, and refreshing your Spring Boot
application whenever changes are made in the code.

:-Spring Boot Actuator


Spring Boot Actuator is a production-ready tool that helps you monitor and manage your
Spring Boot application.
It exposes useful endpoints over HTTP or JMX to check app health, metrics, environment,
logs, and more.

What is Auto-Configuration in Spring Boot?


• Auto-Configuration is a Spring Boot feature that automatically configures your
application based on the dependencies present in your classpath and default
configurations.
• Instead of writing long XML/Java configuration manually, Spring Boot guesses what
you need and sets it up automatically.

Core Spring Annotations


1. @Component
• Use: Marks a class as a Spring-managed bean (generic stereotype).
• Example:
• @Component
• public class MyService { }
• Why: Spring automatically detects it during component scanning and registers it in
the application context.
• Methods: No methods, but has an optional value attribute (bean name).
2. @Controller
• Use: Marks a class as a Spring MVC Controller (handles web requests).
• Why: Tells Spring this class will return views (JSP/HTML).
• Methods: No methods, but works with mappings (@RequestMapping,
@GetMapping, etc.).

3. @RestController
• Use: Combination of @Controller + @ResponseBody.
• Why: Directly returns JSON/XML instead of view pages.
• Example:
• @RestController
• public class ProductController { }

4. @Service
• Use: Marks a class as a service (business logic layer).
• Why: Improves readability and makes it clear this bean holds business logic.

5. @Repository
• Use: Marks a class as DAO (Data Access Object).
• Why: Helps Spring translate database exceptions into Spring DataAccessException.

6. @Autowired
• Use: Automatically injects bean dependencies.
• Example:
• @Autowired
• private ProductDao productDao;
• Methods (attributes):
o required = true/false → If false, no error if bean not found.

7. @Qualifier
• Use: Used with @Autowired to resolve conflicts when multiple beans of same type
exist.
• Example:
• @Autowired
• @Qualifier("myBean")
• private ProductDao productDao;

8. @Value
• Use: Injects values from [Link] or hardcoded.
• Example:
• @Value("${[Link]}")
• private String appName;

9. @Configuration
• Use: Marks a class as a source of Spring bean definitions.
• Why: Replaces XML configuration.
• Example:
• @Configuration
• public class AppConfig {
• @Bean
• public MyService myService() {
• return new MyService();
• }
• }

10. @Bean
• Use: Declares a bean inside a @Configuration class.
• Why: Manually register a bean.
• Methods: Has name and initMethod/destroyMethod attributes.
Spring MVC Annotations
11. @RequestMapping
• Use: Maps HTTP requests to handler methods.
• Example:
• @RequestMapping(value="/products", method=[Link])
• public List<Product> getProducts() { ... }
• Methods (attributes):
o value / path → URL mapping
o method → GET, POST, PUT, DELETE
o params → Request parameters
o headers → Request headers

12. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping


• Use: Shortcut annotations for HTTP methods (introduced in Spring 4.3).
• Example:
• @GetMapping("/products/{id}")
• public Product getProduct(@PathVariable int id) { ... }

13. @PathVariable
• Use: Extracts values from URI.
• Example:
• @GetMapping("/products/{id}")
• public Product getProduct(@PathVariable("id") int id) { ... }

14. @RequestParam
• Use: Extracts query parameters.
• Example:
• @GetMapping("/search")
• public List<Product> search(@RequestParam String name) { ... }
• Attributes:
o value → Parameter name
o required → true/false
o defaultValue

15. @RequestBody
• Use: Binds request JSON → Java object.
• Example:
• @PostMapping("/products")
• public Product save(@RequestBody Product product) { ... }

16. @ResponseBody
• Use: Converts return object → JSON/XML. (Already included in @RestController).

Spring Boot Annotations


17. @SpringBootApplication
• Use: Entry point annotation. Combines:
o @Configuration
o @EnableAutoConfiguration
o @ComponentScan
• Why: Eliminates extra config.
• Example:
• @SpringBootApplication
• public class MyApp {
• public static void main(String[] args) {
• [Link]([Link], args);
• }
• }

18. @EnableAutoConfiguration
• Use: Tells Spring Boot to auto-configure beans based on dependencies in classpath.

19. @ComponentScan
• Use: Tells Spring where to scan for beans.
• Example:
• @ComponentScan("[Link]")

20. @EnableJpaRepositories
• Use: Enables Spring Data JPA repositories.

21. @Entity
• Use: Marks a class as a JPA entity (mapped to DB table).
• Example:
• @Entity
• public class Product { }

22. @Table
• Use: Maps entity → database table (custom name).
• Example:
• @Table(name="product_table")

23. @Id, @GeneratedValue


• Use: Primary key & auto-generation strategy.
• Example:
• @Id
• @GeneratedValue(strategy = [Link])
• private int id;

24. @Column
• Use: Customize column properties.
• Attributes: name, nullable, length, unique.

25. @Transactional
• Use: Manages transactions (commit/rollback).
• Example:
• @Transactional
public void saveProduct(Product p) { ... }

You might also like