Advance Java Notes
Advance Java Notes
• 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.
• 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:
• 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.
• 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]
• 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] Statement:
We can create statement in 2 ways
[Link]
[Link]
[Link]
Statement statement = [Link]();]
[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] ():
• 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:
• 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.
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.
import [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]();
// 5. Close connection
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
package [Link];
import [Link].*;
import [Link];
try {
// Step 1: Load PostgreSQL Driver
[Link]("[Link]");
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 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]("👋 Goodbye!");
return;
default:
} catch (Exception e) {
[Link]();
}
}
}
Servlet
What is Server?
What is Web-Application?
Any application that requires internet and run on server.
Servlet interface
Generally we do not prefer implementing Servlet interface for creating Servlet class,we go
for extending GenericServlet class.
GenericServlet class
--------------------------------------------------------------------------------------------------------------------------
How to create maven for servlet?
Add dependency
Browser--maven repository--search Servlet api 4.0.1--copy and paste it in [Link] between
dependencies tag
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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
<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>
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@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>
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];
@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>
--------------------------------------------------------------------------------------------------------------------------
Printwriter
--------------------------------------------------------------------------------------------------------------------------
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>
@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>");
}
<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>
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>
@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>");
<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>
For handling request sent by the client HttpServlet class provides following methods:
• [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.
--------------------------------------------------------------------------------------------------------------------------
<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];
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];
@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
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];
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];
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>
--------------------------------------------------------------------------------------------------------------------------
</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
• 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
--------------------------------------------------------------------------------------------------------------------------
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]();
String name=[Link]();
if([Link]("pi")) {
[Link](0);
[Link](cookie);
}
}
}
}
<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>
--------------------------------------------------------------------------------------------------------------------------
[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 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.
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 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).
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.
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.
Entity class
a Java class whose objects (instances) are mapped to a table in the database.
Rules to create an Entity class
• 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.
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:
• 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
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
@JoinColumn
--used to merge the columns in database.
when we use @JoinColumn in opposit class we have to use mappedby="ref" mandatorily.
[Link]
<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.
• 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.
• 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.
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.
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
---------------------------------------------------------------------
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
EntityManager em = [Link]();
[Link]().begin();
AUTO Hibernate picks the strategy based on the Could use IDENTITY,
database dialect. SEQUENCE, or TABLE.
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.
🔹 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.
🔹 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.
🔹 5. UUID (Hibernate-specific)
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
Good for distributed systems.
Summary
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
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).
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")
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) { ... }