0% found this document useful (0 votes)
142 views181 pages

20 Spring Boot

Spring boot

Uploaded by

Anil Chowdary
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)
142 views181 pages

20 Spring Boot

Spring boot

Uploaded by

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

Introduction to

Spring Boot

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Introduction to Spring Boot

2 Hello World - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:

 Introduction to Spring Boot

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Introduction to Spring Boot

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


What is Spring Boot?
 Spring Boot is a module of the Spring Framework.

 It is used to create stand-alone, production-grade Spring Based


Applications with minimum efforts.

 It is developed on top of the core Spring Framework.

 Spring Boot follows a layered architecture in which each layer


communicates with the layer directly below or above it.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Spring Boot vs Spring
 Spring: Spring framework is the most popular application development
framework of Java. The main feature of the Spring Framework
is dependency Injection or Inversion of Control (IoC). With the help of
Spring Framework, we can develop a loosely coupled application. It is
better to use if application type or characteristics are purely defined.

 Spring Boot: Spring Boot is a module of Spring Framework. It allows us


to build a stand-alone application with minimal or zero configurations. It is
better to use if we want to develop a simple Spring-based application or
RESTful services.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Spring Boot vs Spring MVC

 Spring Boot: Spring Boot makes it easy to quickly bootstrap and start
developing a Spring-based application. It avoids a lot of boilerplate code.
It hides a lot of complexity behind the scene so that the developer can
quickly get started and develop Spring-based applications easily.

 Spring MVC: Spring MVC is a Web MVC Framework for building web
applications. It contains a lot of configuration files for various capabilities.
It is an HTTP oriented web application development framework.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7


Spring Boot Layers
 Before understanding the Spring Boot Architecture, we must know the
different layers and classes present in it. There are four layers in Spring
Boot are as follows:

 Presentation Layer
 Business Layer
 Persistence Layer
 Database Layer

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Spring Boot Layers

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Spring Boot Layers
 Presentation Layer: The presentation layer handles the HTTP requests,
translates the JSON parameter to object, and authenticates the request and
transfer it to the business layer. In short, it consists of views i.e., frontend
part.
 Business Layer: The business layer handles all the business logic. It
consists of service classes and uses services provided by data access layers.
It also performs authorization and validation.
 Persistence Layer: The persistence layer contains all the storage logic and
translates business objects from and to database rows.
 Database Layer: In the database layer, CRUD (create, retrieve, update,
delete) operations are performed.
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10
Spring Boot Flow Architecture

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Spring Boot Flow Architecture
 Now we have validator classes, view classes, and utility classes.
 Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc.
The architecture of Spring Boot is the same as the architecture of Spring MVC,
except one thing: there is no need for DAO and DAOImpl classes in Spring boot.
 Creates a data access layer and performs CRUD operation.
 The client makes the HTTP requests.
 The request goes to the controller, and the controller maps that request and handles
it. After that, it calls the service logic if required.
 In the service layer, all the business logic performs. It performs the logic on the
data that is mapped to JPA with model classes.
 A JSP page is returned to the user if no error occurred.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


What is Spring Initializr?
 Spring Initializr is a web-based tool provided by the Pivotal Web Service.

 With the help of Spring Initializr, we can easily generate the structure of
the Spring Boot Project.

 It offers extensible API for creating JVM-based projects.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Hello World

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14


Spring Boot Project Creation.
 Using STS :

 Using Spring Initializr : start.spring.io

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


Spring Boot Project Structure.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


Spring Boot – Hello World.
package com.wipro.pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SbHelloWorldApplication {

public static void main(String[] args) {


SpringApplication.run(SbHelloWorldApplication.class, args);
}
}

package com.wipro.pack;
import org.springframework.web.bind.annotation.RequestMapping;
import import org.springframework.stereotype.Controller;
@Controller
public class HelloController {

@RequestMapping("/hello")
public String sayHello() {
return "Hello World";
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Summary
In this session, you have learned about:
 Introduction to Spring Boot

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19


Spring Boot
Dependency
Injection

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Dependency Injection

2 Singleton Bean Scope

3 Prototype Bean Scope

4 Autowiring

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:

 Understand, what is dependency injection in spring boot.

 Understand, what is auto wiring in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Dependency Injection

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


What is Dependency Injection?

 Dependency Injection is a fundamental aspect of the Spring framework,


through which the Spring container "injects" objects into other objects or
"dependencies".

 Simply put, this allows for loose coupling of components and moves the
responsibility of managing components onto the container.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Dependency Injection Scenarios.
Class Employee Class Laptop

Department dep; HardDisk hd;

Project proj; Battery battery;

Class Department Class HardDisk

Class Project Class Battery

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Spring Boot Dependency Injection.
 Spring Container:
When we are running a Spring Boot application, by default it will create
the Spring Container inside a JVM.
SpringApplication.run() will create a Spring Container. And it will return
an object of “ConfigurableApplicationContext”.
 @Component:
This annotation will tell the Spring Boot to create an object of particular
bean class inside the Spring Container.
 getBean():
By using “ConfigurableApplicationContext” object, we can call a
method getBean() to get a particular bean object from the Spring Container.
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7
Dependency Injection - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Spring Boot Dependency Injection.
package com.wipro.pack;
import org.springframework.stereotype.Component;
@Component
public class Employee {
private int eid;
private String ename;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public void display() {
System.out.println("You got Employee object");
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Spring Boot Dependency Injection.
package com.wipro.pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SbDependencyInjectionApplication {

public static void main(String[] args) {


ConfigurableApplicationContext context = SpringApplication.run(SbDependencyInjectionApplication.class, args);
Employee emp1 = context.getBean(Employee.class);
emp1.display();
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10


Spring Boot Bean Scope

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Spring Boot Bean Scope
The Scope of a bean is a metadata where we can specify which Instance
we would like to get from the container. In Spring we have the
opportunity to choose among five different bean scopes.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


Spring Boot Bean Scope
 Singleton scope
• This is the default scope. It means that the IoC container will only create
exactly one instance of the object defined by that bean definition. The
container stores this particular instance to a cache. Therefore all request
which points to that bean will get this single instance.
 Prototype scope
• If you define a bean as a prototype the IoC container will serve a new
instance from that bean every time you call for it.
 Request scope
• The web container creates a new instance for every independent HTTP
request. Hence, they destroy every time when the call ends.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Spring Boot Bean Scope
 Session scope
• The container returns a new instance for every session. Hence if we call our
controller in the same Session the result will be the same.
 Global-Session scope
• The global session scoped bean instance is shared across your web
application. Hence every call receives the same bean instance. Its similar to
the singleton in normal core applications.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14


Singleton Bean Scope

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


Singleton Bean Scope.
 Singleton scope in the spring framework is the default bean scope in the
spring container.

 It tells the container to exactly create a single instance of the object.

 This single instance is stored in the cache and all the subsequent requests
for that named bean return the cached instance.

 Even if there is no request raised for a bean object also it will create one
instance for the particular bean class.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


Singleton Bean Scope - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Singleton Bean Scope.
package com.wipro.pack;
import org.springframework.stereotype.Component;
@Component
public class Employee {
private int eid;
private String ename;
public Employee() {
System.out.println("Inside Employee Constructor");
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public void display() {
System.out.println("You got Employee object");
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


Singleton Bean Scope.
package com.wipro.pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SbDependencyInjectionApplication {

public static void main(String[] args) {


ConfigurableApplicationContext context = SpringApplication.run(SbDependencyInjectionApplication.class, args);
Employee emp1 = context.getBean(Employee.class);
emp1.display();
Employee emp2 = context.getBean(Employee.class);
emp2.display();
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19


Prototype Bean Scope

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 20


Prototype Bean Scope

 If the scope is set to prototype, the Spring Container creates a new bean
instance of the object every time a request for that specific bean is made.

 The spring container will create an instance for a particular bean class if
the request is raised. Other wise no instance will be created for the
particular bean class.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 21


Prototype Bean Scope - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 22


Prototype Bean Scope.
package com.wipro.pack;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class Employee {
private int eid;
private String ename;
public Employee() {
System.out.println("Inside Employee Constructor");
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public void display() {
System.out.println("You got Employee object");
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 23


Prototype Bean Scope.
package com.wipro.pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SbDependencyInjectionApplication {

public static void main(String[] args) {


ConfigurableApplicationContext context = SpringApplication.run(SbDependencyInjectionApplication.class, args);
Employee emp1 = context.getBean(Employee.class);
emp1.display();
Employee emp2 = context.getBean(Employee.class);
emp2.display();
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 24


Autowiring

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 25


What is Autowiring?

 Autowiring happens by placing an instance of one bean into an instance of


another bean.

 Both classes should be beans.

 i.e. They should be defined to live in the application context or spring


container.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 26


Autowiring - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 27


Autowiring – Example.
package com.wipro.pack; package com.wipro.pack;
import import org.springframework.stereotype.Component;
org.springframework.beans.factory.annotation.Autowired; @Component
import org.springframework.stereotype.Component; public class Department {
@Component private int did;
public class Employee { private String dname;
private int eid; public int getDid() {
private String ename; return did;
@Autowired }
private Department dep; public void setDid(int did) {
//Generate Getters & Setters of eid & ename this.did = did;
public Department getDep() { }
return dep; public String getDname() {
} return dname;
public void setDep(Department dep) { }
this.dep = dep; public void setDname(String dname) {
} this.dname = dname;
public void display() { }
System.out.println("Got Employee Object"); public void display() {
dep.display(); System.out.println("Got Department Object");
} }
} }

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 28


Autowiring – Example.
package com.wipro.pack;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SbAutowiringApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SbAutowiringApplication.class, args);

Employee emp = context.getBean(Employee.class);


emp.display();
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 29


Dependency Injection Conclusion.
@Component @Component
Class Employee Class Laptop
@Autowired @Autowired
Department dep; HardDisk hd;
@Autowired @Autowired
Project proj; Battery battery;

@Component @Component
Class Department Class HardDisk

@Component @Component
Class Project Class Battery

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 30


Summary
In this session, you have learned about:
 What is dependency injection in spring boot.

 What is auto wiring in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 31


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 32


Spring Boot Web
App

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Spring Boot Web App.

2 Spring Boot Web App Using Properties File

3 Spring Boot Web App Accepting Client Data

4 Spring Boot MVC

5 Spring Boot MVC Using Model Object


Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2
Objectives
At the end of this module, you will be able to:

 Understand, How to create a web app in spring boot.


 Understand, How to create a web app using properties file.
 Understand, How the spring boot accepts client data.
 Understand, How to create MVC in spring boot.
 Understand, How to create MVC with model object.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Spring Boot Web App

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


Spring Boot Web App.
 If we want to develop a web application, we need to add the following
dependency in pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
 There are two important features of spring-boot-starter-web:
• It is compatible for web development
• Auto configuration
 Starter of Spring web uses Spring MVC, REST and Tomcat as a default
embedded server.
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5
Spring Boot Web App.
 While creating a spring boot web project, you can add web dependency as
like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Spring Boot Web App.
 Since we are going to use JSP in our example, we need to add the below
dependency in our pom.xml as per our embedded tomcat version.
 Because mainly Spring Boot is concentrating on REST and Micro
Services.
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.33</version>
</dependency>

 Here, we are going to use two annotations @Controller and


@RequestMapping.
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7
How to find out embedded tomcat version

While running the previous example, We can find the


embedded tomcat version from the console like below.

We can get the dependency from the below link


https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Spring Boot Web App - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Spring Boot Web App.
package com.wipro.pack;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebAppController {

@RequestMapping("/home")
public String home() {
return "Home.jsp";
}
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<font color=green><b>Welcome to Home Page</b></font>
</body>
</html>
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10
SB Web App Using Properties File

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Spring Boot Web App Using Properties File.
 In our previous example, We have created Home.jsp file inside “webapp”
folder. Because by default the spring boot will check this folder to find the
view pages.

 Also in our “WebAppController”, we have hard coded the extensions of


view page as “.jsp”.

 In case, If I want to store all my view pages in a separate folder and I want
change the view page extension based on customer requirement with out
touching my Controller then the properties file will come to the picture.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


SB Web App Using Properties File -
Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Spring Boot Web App Using Properties File.
package com.wipro.pack; server.port=8123
import org.springframework.stereotype.Controller; spring.mvc.view.prefix=/views/
import org.springframework.web.bind.annotation.RequestMapping; spring.mvc.view.suffix=.jsp
@Controller
public class WebAppController {

@RequestMapping("/home")
public String home() {
return "Home";
}
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<font color=green><b>Welcome to Home Page</b></font>
</body>
</html>
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14
SB Web App Accepting Client Data

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


SB Web App Accepting Client Data. Home.jsp
<form action="welcome"><font color=green><b>
Enter Your Name : <input type="text"
name="name"/><br>
package com.wipro.pack; <input type="submit" value="Submit"/>
import javax.servlet.http.HttpServletRequest; </form></b></font>
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; Welcome.jsp
@Controller
public class WebAppController { <body>
@RequestMapping("/home") <font color=green><b>Welcome
public String home() { ${name}</b></font>
return "Home";
</body>
}
@RequestMapping("/welcome")
public String welcome(HttpServletRequest req) {
String name = req.getParameter("name");
req.setAttribute("name", name);
return "Welcome";
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


Spring Boot MVC

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Spring Boot MVC. Home.jsp
<form action="welcome"><font color=green><b>
Enter Your Name : <input type="text"
package com.wipro.pack; name="name"/><br>
<input type="submit" value="Submit"/>
import org.springframework.stereotype.Controller;
</form></b></font>
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; Welcome.jsp
@Controller
public class WebAppController { <body>
@RequestMapping("/home") <font color=green><b>Welcome
public String home() { ${name}</b></font>
return "Home"; </body>
}
@RequestMapping("/welcome")
public ModelAndView welcome(@RequestParam("name")
String name) {
ModelAndView mv = new ModelAndView();
mv.addObject("name", name);
mv.setViewName("Welcome");
return mv;
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


SB MVC Using Employee Model
Object

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19


SB MVC Using Employee Model Object.Home.jsp
<form action="welcome"><font color=green><b>
Enter Your Id : <input type="text" name="id"/><br>
package com.wipro.pack;
import org.springframework.stereotype.Controller;
Enter Your Name : <input type="text"
import name="name"/><br>
org.springframework.web.bind.annotation.RequestMapping; Enter Your Salary : <input type="text"
import org.springframework.web.servlet.ModelAndView; name="salary"/><br>
@Controller <input type="submit" value="Submit"/>
public class WebAppController { </form></b></font>
@RequestMapping("/home")
public String home() {
return "Home";
Welcome.jsp
}
@RequestMapping("/welcome")
public ModelAndView welcome(Employee emp) { <body>
ModelAndView mv = new ModelAndView(); <font color=green><b>Welcome ${emp.id} ,
mv.addObject("emp", emp); ${emp.name}, ${emp.salary}</b></font>
mv.setViewName("Welcome"); </body>
return mv;
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 20


SB MVC Using Employee Model Object.
package com.wipro.pack;
public class Employee {
private int id;
private String name;
private int salary;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 21
Summary
In this session, you have learned about:
 What is web app in spring boot.
 How to create a web app using properties file.
 How the spring boot accepts client data.
 How to create MVC in spring boot.
 How to create MVC with Employee model object.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 22


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 23


Spring Boot MVC
JPA H2

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Spring Boot MVC JPA H2

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:

 Understand, How to create a MVC web application by using JPA


and H2 database to perform CRUD operations in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Spring Boot MVC JPA H2

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


What is H2?
 H2 is an open-source lightweight Java database.

 It can be embedded in Java applications or run in the client-server mode.

 Mainly, H2 database can be configured to run as inmemory database,


which means that data will not persist on the disk.

 Because of embedded database it is not used for production development,


but mostly used for development and testing.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Spring Boot MVC JPA H2.
 We will create a spring boot project along with web, jpa and h2
dependencies. Like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Spring Boot MVC JPA H2.
 We will create a model class “Employee” and Home.jsp like below.
package com.wipro.pack.model;
public class Employee {
private int eid;
private String ename;
private int esalary;
//Getters & Setters
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", esalary=" + esalary + "]";
}
}

<body>
<form action="AddEmployee">
Employee Id <input type="text" name="eid"/><br>
Employee Name <input type="text" name="ename"/><br>
Employee Salary <input type="text" name="esalary"/><br>
<input type="Submit" value="Add Employee"/>
</form>
</body>

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7


Spring Boot MVC JPA H2.
 We will create controller “EmployeeController” like below.
package com.wipro.pack.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmployeeController {
@RequestMapping("/home")
public String home() {
return "Home";
}
}

 Now our output will be like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Spring Boot MVC JPA H2.
 Now we will enable H2 data base in properties file like below.
server.port=8123
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:valan

 Relaunch our application and check the url - localhost:8123/h2-console


and test connection.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Spring Boot MVC JPA H2.
 Now click connect to connect with our database. You will get like below.

 You can look at our database, there is no table is created.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10


Spring Boot MVC JPA H2.
 To create a table in H2 data base by using our Employee model, We will
use two annotations @Entity and @Id like below.
package com.wipro.pack.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int eid;
private String ename;
private int esalary;
//Getters & Setters
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", esalary=" + esalary + "]";
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Spring Boot MVC JPA H2.
 Relaunch our application and check the H2 data base. Now we are getting
the table.

 But there is no record.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


Spring Boot MVC JPA H2.
 In case, If we want to execute any pre handed queries. Then we need to
create a file “data.sql” and inside this file we can have our pre handed
queries. Like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Spring Boot MVC JPA H2.
 Now relaunch our application and test our data base, we will get one
record as like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14


Spring Boot MVC JPA H2.
 Just we have look on our “EmployeeController” and “Home.jsp”. And we
will insert a employee details via our application.
package com.wipro.pack.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EmployeeController {
@RequestMapping("/home")
public String home() {
return "Home";
}
}

<body>
<form action="AddEmployee">
Employee Id <input type="text" name="eid"/><br>
Employee Name <input type="text" name="ename"/><br>
Employee Salary <input type="text" name="esalary"/><br>
<input type="Submit" value="Add Employee"/>
</form>
</body>
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15
Spring Boot MVC JPA H2.
 Now we will create a “EmployeeDao” interface like below.
package com.wipro.pack.dao;

import org.springframework.data.repository.CrudRepository;

import com.wipro.pack.model.Employee;

public interface EmployeeDao extends CrudRepository<Employee, Integer>{

 Here we are extending an interface “CrudRepository”. It will provide all


CRUD operations functionality. We need not write any code for this
CRUD operations.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


Spring Boot MVC JPA H2.
 Now we will use this “EmployeeDao” interface in our
“EmployeeController” to insert a record into our H2 database employee
table like below.
@Controller
public class EmployeeController {
@Autowired
EmployeeDao dao;
@RequestMapping("/home")
public String home() {
return "Home";
}
@RequestMapping("/AddEmployee")
public ModelAndView addEmployee(Employee emp) {
ModelAndView mv = new ModelAndView();
dao.save(emp);
mv.addObject("message", "Record Inserted");
mv.setViewName("Home");
return mv;
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Spring Boot MVC JPA H2.
 Relaunch our application and test the output.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


Spring Boot MVC JPA H2.

 Other CRUD methods from “CrudRepository” interface.


• count()
• delete(Entity entity)
• deleteAll()
• deleteById(Integer id)
• findAll()
• findById(Integer id)

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19


Summary
In this session, you have learned about:
 How to create a MVC web application by using JPA and H2
database to perform CRUD operations in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 20


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 21


Spring Boot MVC
JPA H2 Query
Methods

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Spring Boot MVC JPA H2 Query Methods

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:

 Understand, What is query methods in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Spring Boot MVC JPA H2 Query
Methods

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


Crud Repository Interface
 The CRUD methods from “CrudRepository” interface are.
• save(Entity entity)
• count()
• delete(Entity entity)
• deleteAll()
• deleteById(Integer id)
• findAll()
• findById(Integer id)

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Scenario - 1

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Scenario - 1
 Let us consider our model class is like below.
package com.wipro.pack.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int eid;
private String ename;
private int esalary;
//Getters & Setters
@Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", esalary=" + esalary + "]";
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7


Scenario - 1
 Also let us load some records in H2 Employee table by using "data.sql"
file. For example like below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Scenario - 1
 In this case, If we want to find or delete any employee records by using
"eid" then I can use "CrudRepository" interface methods findById() and
deleteById().

 Suppose, If we want to find or delete any employee records by using


“ename” or “esalary” then "CrudRepository" interface methods will not
help. Because there is no such a method.

 Now will see the solution for this scenario in the next slide.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


Scenario - 1
 Below is the solution.
package com.wipro.pack.dao;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.wipro.pack.model.Employee;
public interface EmployeeDao extends CrudRepository<Employee, Integer>{
List<Employee> findByEname(String name);
}

 Just to check the result, will have a controller like below.


@Controller
public class EmployeeController {
@Autowired
EmployeeDao dao;
@RequestMapping("/home")
public String home() {
System.out.println(dao.findByEname("valan"));
return "";
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10
Scenario - 1
 Here the rule is that the method must begin with findBy or getBy
and then the property name.
List<Employee> findByEname(String name);

List<Employee> getByEname(String name);

 Same way, you can have your own deleteBy or removeBy method.
void deleteByEname(String name);

void deleteByEsalary(int salary);

void removeByEsalary(int salary);

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


Scenario - 2

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


Scenario - 2
 In this case, If we want to find or delete any employee records by using
some conditions.

 Like salary greater than or less than.

 Will see the solution for this scenario in the next slide.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


Scenario - 2
 Below is the solution for our “EmployeeDao” interface.
List<Employee> findByEsalaryGreaterThan(int salary);

List<Employee> findByEsalaryLessThan(int salary);

List<Employee> deleteByEsalaryGreaterThan(int salary);

List<Employee> deleteByEsalaryLessThan(int salary);

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14


Scenario - 3

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


Scenario - 3
 If we want to write our own query. Then we can use @Query to write
JPQL.

@Query("from employee where ename=?1 order by esalary")


List<Employee> findByEnameSorted(String name);

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


Summary
In this session, you have learned about:
 What is query methods in spring boot.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


Spring Boot MVC
JPA H2 REST

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 1


Agenda

Introduction to Web Services.

2 Introduction to RESTful Web Services.

3 Spring Boot MVC JPA H2 REST

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 2


Objectives
At the end of this module, you will be able to:

 Understand, What is RESTful web services.


 Understand, HTTP Methods.
 Understand, How to create RESTful web services by using Spring
Boot and H2 database.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 3


Introduction to Web Services

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 4


What is Web Services?

 A web service is a collection of open protocols and standards used for


exchanging data between applications or systems.

 Software applications written in various programming languages and


running on various platforms can use web services to exchange data over
computer networks.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 5


Benefits of Web Services?
 Loosely Coupled
Each service exists independently of the other services. Individual pieces
of the application to be modified without impacting unrelated areas.
 Ease of Integration
Data is isolated between applications. Web Services act as glue between
these and enable easier communications within and across organizations.
 Service Reuse
Takes code reuse a step further. A specific function within the domain is
only ever coded once and used over and over again by consuming
applications.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6


Web Services Architecture.

 The simplest web service system has two participants:


• A service producer (provider)
• A service consumer (requester)

 The provider presents the interface and implementation of the service, and
the requester uses the Web service.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 7


Types of Web Services.

 There are mainly two types of web services.


• SOAP web services.
• RESTful web services

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 8


Introduction to RESTful Web
Services

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 9


What is RESTful Web Services?

 REST is used to build Web services that are lightweight, maintainable, and
scalable in nature.
 A service which is built on the REST architecture is called a RESTful
service.
 The underlying protocol for REST is HTTP, which is the basic web
protocol.
 REST stands for REpresentational State Transfer.
 REST uses various representation to represent a resource like text, JSON,
XML.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 10


SOAP vs REST

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 11


HTTP Methods

GET POST PUT DELETE

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 12


REST Media Types

 Media types allow an API to inform the client how to interpret the data in
the payload.

 Examples:
MediaType.TEXT_HTML
MediaType.TEXT_PLAIN
MediaType.TEXT_XML
MediaType.APPLICATION_JSON

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 13


REST GET Method

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 14


What is GET Method?

 This request is used to get a resource from a server.

 If we perform a GET request, the server looks for the data we requested
and sends it back to us.

 In other words, a GET request performs a READ operation.

 This is the default request method.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 15


REST GET Method - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 16


REST GET Method – Example.

package com.wipro.pack.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Employee {
@Id
private int eid;
private String ename;
private int esalary;

//Getters & Setters

@Override
public String toString() {
return "Employee [eid=" + eid + ", ename="
+ ename + ", esalary=" + esalary + "]";
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 17


REST GET Method – Example.
 Just preloaded some of the records by using "Employee" model class and
"data.sql" file. Now our H2 data base will be as below.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 18


REST GET Method – Example.
package com.wipro.pack.controller; Note:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; @RestController = @Controller +
import org.springframework.web.bind.annotation.PathVariable; @ResponseBody
import org.springframework.web.bind.annotation.RestController;
import com.wipro.pack.dao.EmployeeDao;
@RestController
In case of @Controller, The return value will be
public class EmployeeController { consider as a View Page name.
@Autowired
But here we are not returning view page name.
EmployeeDao dao;
We are returning a data.
@GetMapping("/getEmployees")
public String getEmployees() { So If it is a @Controller then we have to add
return dao.findAll().toString();
} @ResponseBody annotations.

@GetMapping("/getEmployee/{eid}") But @RestController will take it by default.


public String getEmployee(@PathVariable("eid")
Integer eid) {
return dao.findById(eid).toString();
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 19


REST GET Method – Example.
package com.wipro.pack.dao;

import org.springframework.data.repository.CrudRepository;

import com.wipro.pack.model.Employee;

public interface EmployeeDao extends CrudRepository<Employee, Integer>{

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 20


REST GET Method – Example.
 If we look at our output. We can see it is displaying a List<Employee> as
String.

 But We want to produce the output as json format.

 Spring Boot will perform this by default.

 To get this, Our dao should extend JpaRepository instead of


CrudRepository.

 JpaRepository is extending CrudRepository.


Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 21
REST GET Method – Example.
package com.wipro.pack.controller;
import java.util.List; import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.wipro.pack.dao.EmployeeDao; import com.wipro.pack.model.Employee;
@RestController
public class EmployeeController {

@Autowired
EmployeeDao dao;

@GetMapping("/getEmployees")

public List<Employee> getEmployees() {


return dao.findAll();
}

@GetMapping("/getEmployee/{eid}")
public Optional<Employee> getEmployee(@PathVariable("eid") Integer eid) {
return dao.findById(eid);
}
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 22


REST GET Method – Example.

package com.wipro.pack.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.wipro.pack.model.Employee;

public interface EmployeeDao extends JpaRepository<Employee, Integer>{

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 23


Post Man

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 24


What is Post Man?

 Postman is a popular API client that makes it easy for developers to create,
share, test and document APIs.

 This is done by allowing users to create and save simple and complex
HTTP/s requests, as well as read their responses.

 The result - more efficient and less tedious work.

 https://www.postman.com/downloads/
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 25
REST GET Method – Example.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 26


REST Post Method

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 27


What is POST Method?

 This request is used to create a new resource on a server.

 If we perform a POST request, the server creates a new entry in the


database and tells us whether the creation is successful.

 In other words, a POST request performs an CREATE operation.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 28


REST Post Method - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 29


REST Post Method – Example.
@RestController
public class EmployeeController {

@Autowired
EmployeeDao dao;
package com.wipro.pack.dao;
@GetMapping("/getEmployees")
import
public List<Employee> getEmployees() {
org.springframework.data.jpa.repository.JpaRepository;
return dao.findAll();
}
import com.wipro.pack.model.Employee;
@GetMapping("/getEmployee/{eid}")
public interface EmployeeDao extends JpaRepository<Employee,
public Optional<Employee>
Integer>{
getEmployee(@PathVariable("eid") Integer eid) {
return dao.findById(eid);
}
}

@PostMapping("/createEmployee")
public Employee createEmployee(Employee emp) {
return dao.save(emp);
}

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 30


REST Post Method – Example.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 31


REST Put Method

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 32


What is PUT Method?

 This request is used to update a resource on a server.

 If we perform a PUT request, the server updates an entry in the database


and tells us whether the update is successful.

 In other words, a PUT request performs an UPDATE operation.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 33


REST Put Method - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 34


REST Put Method – Example.
@RestController
public class EmployeeController {

@Autowired
EmployeeDao dao;
package com.wipro.pack.dao;
@GetMapping("/getEmployees")
public List<Employee> getEmployees() {
return dao.findAll();
import
}
org.springframework.data.jpa.repository.JpaRepository;
@GetMapping("/getEmployee/{eid}")
import com.wipro.pack.model.Employee;
public Optional<Employee>
getEmployee(@PathVariable("eid") Integer eid) {
public interface EmployeeDao extends JpaRepository<Employee,
return dao.findById(eid);
Integer>{
}

@PostMapping("/createEmployee") }
public Employee createEmployee(Employee emp) {
return dao.save(emp);
}

@PutMapping("/updateEmployee")
public Employee updateEmployee(Employee emp) {
return dao.save(emp);
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 35
REST Put Method – Example.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 36


REST Delete Method

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 37


What is DELETE Method?

 This request is used to delete a resource from a server.

 If we perform a DELETE request, the server deletes an entry in the


database and tells us whether the deletion is successful.

 In other words, a DELETE request performs a DELETE operation.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 38


REST Delete Method - Example

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 39


REST Delete Method – Example.
@RestController
public class EmployeeController {
@Autowired
EmployeeDao dao;
@GetMapping("/getEmployees")
public List<Employee> getEmployees() { package com.wipro.pack.dao;
return dao.findAll();
}
@GetMapping("/getEmployee/{eid}") import
public Optional<Employee> org.springframework.data.jpa.repository.JpaRepository;
getEmployee(@PathVariable("eid") Integer eid) {
return dao.findById(eid); import com.wipro.pack.model.Employee;
}
@PostMapping("/createEmployee") public interface EmployeeDao extends JpaRepository<Employee,
public Employee createEmployee(Employee emp) { Integer>{
return dao.save(emp);
}
}
@PutMapping("/updateEmployee")
public Employee updateEmployee(Employee emp) {
return dao.save(emp);
}
@DeleteMapping("/deleteEmployee/{eid}")
public void deleteEmployee(@PathVariable("eid")
Integer eid) {
dao.deleteById(eid);
}
}
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 40
REST Delete Method – Example.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 41


Summary
In this session, you have learned about:
 What is RESTful web services.
 Various HTTP Methods in web services.
 How to create RESTful web services by using Spring Boot and H2
database.

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 42


Thank you

Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 43


Spring Boot JPA Application

1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
Note: You can create using STS or Eclipse
2. Create a Department class with required attributes
3. Enable H2 database in properties file
4. Run your application and check database connection – you’ll notice that no tables are available
5. Annotate the Department class with @Entity and the primary key field with @Id
6. Create the DepartmentDAO interface which extends from CRUDRepository
7. Create the DepartmentService Interface
8. Create the DepartmentServiceImpl class and provide Implementation
9. Create the DepartmentController class and required methods
10. Add Tomcat Jasper Dependency in pom.xml
11. Create view pages and test your application

Let us start working step by step:

1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2

Click finish to create the Project

2. Create a Department class with required attributes under com.wipro.bean package

package com.wipro.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

Sensitivity: Internal & Restricted


import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Department {


private int deptno;
private String dname;
private String loc;
private double budget;
public Department() {
}
public Department(int deptno, String dname, String loc, double budget) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.budget = budget;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}

public double getBudget() {


return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
}

2. Enable H2 database in properties file

server.port=8123
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:sample

Sensitivity: Internal & Restricted


4. Add H2 dependency,JSTL,Tomcat-jasper and devtools in the POM file
Ensure all the below given dependency is there in your POM file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.37</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional> </dependency>

5. Run your application and check database connection – you’ll notice that no tables are available
Once the application has started, Goto to browser and give
http://localhost:8123/h2-console

Sensitivity: Internal & Restricted


6. Annotate the Department class with @Entity and the primary key field with @Id

package com.wipro.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptno;
private String dname;
private String loc;
private double budget;
public Department() {
}
public Department(int deptno, String dname, String loc, double budget) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.budget = budget;
}
public int getDeptno() {
return deptno;
}

Sensitivity: Internal & Restricted


public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}

public double getBudget() {


return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
}

Now once you save the changes devtools automatically restarts the server now again connect to H2 and
you can find the Department table

7. Create the DepartmentDAO interface under the package com.wipro.dao which extends from
CRUDRepository

package com.wipro.dao;

import java.util.List;

import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

Sensitivity: Internal & Restricted


import com.wipro.bean.Department;

public interface DepartmentDAO extends CrudRepository<Department, Integer>{


//No declaration required for basic CRUD operations
}

Here we don’t need to implement the DepartmentDao interface and SpringBoot gives us
internal implementation through CrudRepository.

8. Create the DepartmentService Interface

package com.wipro.service;

import java.util.List;

import com.wipro.bean.Department;

public interface DepartmentService {

public Department save(Department d);


public Department findById(Integer id);
public Department update(Department d);
public void deleteById(Integer id);
public List<Department> findAll();
}

9. Create the DepartmentServiceImpl class and provide Implementation

package com.wipro.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wipro.bean.Department;
import com.wipro.dao.DepartmentDAO;

/**
*Only insert and show All is implemented
*You are expected to write and test the codes of other operations

Sensitivity: Internal & Restricted


*/

@Service
public class DepartmentServiceImpl implements DepartmentService {

@Autowired
DepartmentDAO dao;

@Override
public Department save(Department d) {
return dao.save(d);
}
@Override
public Department findById(Integer id) {
// TODO Auto-generated method stub
return dao.findById(id).get();
}
@Override
public List<Department> findAll() {
List<Department> list = new ArrayList<Department>();
dao.findAll().forEach(dept->list.add(dept));
return list;
}
@Override
public void deleteById(Integer id) {
dao.deleteById(id);
}

@Override
public Department update(Department d) {
return dao.save(d);
}

10. Create the DepartmentController class and required methods

package com.wipro.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

Sensitivity: Internal & Restricted


import com.wipro.bean.Department;
import com.wipro.service.DepartmentService;

@Controller
public class DepartmentController {
@Autowired
DepartmentService service;

@RequestMapping("/menu")
public String showMenu(Model m) {
m.addAttribute("list", service.findAll());
return "Menu";
}

@RequestMapping("/insertForm")
public String showInsertForm(Model m) {
m.addAttribute("dept", new Department());
return "InsertForm";
}

@RequestMapping("/saveForm")
public String saveForm(@ModelAttribute("dept") Department dept, Model m) {
service.save(dept);
m.addAttribute("msg", "Inserted/Updated Successfully");
m.addAttribute("list", service.findAll());
return "Menu";
}

@RequestMapping("/showAll")
public String showAll(Model m) {
m.addAttribute("list", service.findAll());
return "ShowAll";
}

11. Create view pages and test your application

Menu.jsp Page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>

Sensitivity: Internal & Restricted


<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>

<br/>
${msg }
<center>
<h2>Menu Items</h2>
<a href="/insertForm" class="btn btn-primary">Insert an Departments</a>
&nbsp;&nbsp;&nbsp;
<a href="/showForm" class="btn btn-primary">Show an Departments</a>
&nbsp;&nbsp;&nbsp;
<a href="/updateForm" class="btn btn-primary">Update an Departments</a>
&nbsp;&nbsp;&nbsp;
<a href="/deleteForm" class="btn btn-primary">Delete an Departments</a>
&nbsp;&nbsp;&nbsp;
<a href="/showAll" class="btn btn-primary">Show All Departments</a> <br/><br/>

</center>
<c:if test = "${list.size()> 0}">
<center><h2>Department List</h2></center>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>Budget</th>

</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
<td>${dep.loc}</td>
<td>${dep.budget}</td>

</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

InsertForm.jsp Page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

Sensitivity: Internal & Restricted


<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="container pt-3">
<form:form action="saveForm" modelAttribute="dept">
<div class="form-group">
<label for="dname">Department Name:</label>
<form:input path="dname" class="form-control"/>
</div>
<div class="form-group">
<label for="loc">Location:</label>
<form:input path="loc" class="form-control"/>
</div>
<div class="form-group">
<label for="loc">Budget:</label>
<form:input path="budget" class="form-control"/>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
</body>
</html>

ShowAll.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<h2>Department List</h2>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>

</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>

Sensitivity: Internal & Restricted


<td>${dep.loc}</td>

</tr>
</c:forEach>
</table>
</body>
</html>

Output:

Click on insert

Sensitivity: Internal & Restricted


Spring Boot JPA Application

1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2
Note: You can create using STS or Eclipse
2. Create a Department class with required attributes and Annotate the Department class with
@Entity and the primary key field with @Id
3. Enable H2 database in properties file
4. Create the DepartmentDAO interface which extends from CRUDRepository
5. Create the DepartmentService Interface
6. Create the DepartmentServiceImpl class and provide Implementation
7. Create the DepartmentController class and required methods
8. Create view pages and test your application

Let us start working step by step:

1. Create a Spring Boot starter project with Spring Web, Spring Data JPA and H2

Click finish to create the Project

2. Create a Department class with required attributes under com.wipro.bean package

package com.wipro.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

Sensitivity: Internal & Restricted


@Entity
public class Department {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int deptno;
private String dname;
private String loc;
private double budget;
public Department() {
}
public Department(int deptno, String dname, String loc, double budget) {
super();
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.budget = budget;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}

public double getBudget() {


return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
}

2. Enable H2 database in properties file

server.port=8123
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:sample

Sensitivity: Internal & Restricted


4. Add H2 dependency,JSTL,Tomcat-jasper and devtools in the POM file
Ensure all the below given dependency is there in your POM file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.37</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional> </dependency>

5. Run your application and check database connection – you’ll notice that no tables are available
Once the application has started, Goto to browser and give
http://localhost:8123/h2-console

Sensitivity: Internal & Restricted


connect to H2 and you can find the Department table

6. Create the DepartmentDAO interface under the package com.wipro.dao which extends from
CRUDRepository

package com.wipro.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

Sensitivity: Internal & Restricted


import com.wipro.bean.Department;

public interface DepartmentDAO extends CrudRepository<Department, Integer>{


public List<Department> getByDname(String dname);
@Transactional
public void deleteByDname(String dname);
public List<Department> findByBudgetGreaterThan(double budget);
@Query("from Department order by budget")
List<Department> findByDname();
}

7. Create the DepartmentService Interface

package com.wipro.service;

import java.util.List;

import com.wipro.bean.Department;

public interface DepartmentService {

public Department save(Department d);


public List<Department> findAll();
public List<Department> getByDname(String dname);
public boolean deleteByDname(String dname);
public List<Department> findByBudgetGreaterThan(double budget);
public List<Department> findByDname();
}

8. Create the DepartmentServiceImpl class and provide Implementation

package com.wipro.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wipro.bean.Department;
import com.wipro.dao.DepartmentDAO;

Sensitivity: Internal & Restricted


@Service
public class DepartmentServiceImpl implements DepartmentService {

@Autowired
DepartmentDAO dao;

@Override
public Department save(Department d) {
return dao.save(d);
}

@Override
public List<Department> findAll() {
List<Department> list = new ArrayList<Department>();
dao.findAll().forEach(dept->list.add(dept));
return list;
}

@Override
public List<Department> getByDname(String dname) {
return dao.getByDname(dname);
}

@Override
public boolean deleteByDname(String dname) {
dao.deleteByDname(dname);
return true;

@Override
public List<Department> findByBudgetGreaterThan(double budget) {
return dao.findByBudgetGreaterThan(budget);
}

@Override
public List<Department> findByDname(){
return dao.findByDname();
}
}

Sensitivity: Internal & Restricted


9. Create the DepartmentController class and required methods

package com.wipro.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wipro.bean.Department;
import com.wipro.service.DepartmentService;

@Controller
public class DepartmentController {
@Autowired
DepartmentService service;

@RequestMapping("/menu")
public String showMenu(Model m)
{
m.addAttribute("list",service.findAll());
return "Menu";
}

@RequestMapping("/insertForm")
public String showInsertForm(Model m)
{
m.addAttribute("dept", new Department());
return "InsertForm";
}

@RequestMapping("/saveForm")
public String saveForm(@ModelAttribute ("dept") Department dept,Model m)
{
service.save(dept);
m.addAttribute("list",service.findAll());
return "Menu";
}

@RequestMapping("/showByName")
public String showByNamePage() {
return "ShowByName";
}

Sensitivity: Internal & Restricted


@RequestMapping("/deleteByName")
public String deleteByNamePage() {
return "DeleteByName";
}

@RequestMapping("/byname")
public String showByName(@RequestParam("txtDname") String dname, Model m) {
m.addAttribute("list",service.getByDname(dname));
return "ShowByName";
}
@RequestMapping("/deletebyname1")
public String deletByName(@RequestParam("txtDname") String dname,Model m) {
if(service.deleteByDname(dname))
m.addAttribute("msg", "Deleted Successfully");
else
m.addAttribute("msg", "Delete UnSuccessfull");
m.addAttribute("list",service.findAll());
return "Menu";
}
@RequestMapping("/getBudget")
public String getBudget() {
return "ShowByBudget";
}
@RequestMapping("/showByBudget")
public String showByBudget(@RequestParam("txtBudget") double budget,Model m) {
m.addAttribute("list",service.findByBudgetGreaterThan(budget));
return "Menu";
}
@RequestMapping("/orderedList")
public String orderList(Model m) {
m.addAttribute("list",service.findByDname());
return "Menu";
}
}

10. Create view pages and test your application

Menu.jsp Page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>

Sensitivity: Internal & Restricted


<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>

<br/>
${msg }
<center>
<h2>Menu Items</h2>
<a href="/insertForm" class="btn btn-primary">Insert an Departments</a>
&nbsp;&nbsp;&nbsp;
<a href="/showByName" class="btn btn-primary">Show By Name</a> &nbsp;&nbsp;&nbsp;
<a href="/deleteByName" class="btn btn-primary">Delete By Name</a>&nbsp;&nbsp;&nbsp;
<a href="/orderedList" class="btn btn-primary">Order By Budget</a>&nbsp;&nbsp;&nbsp;
<a href="/getBudget" class="btn btn-primary">Show By Budget</a><br/><br/>
</center>
<c:if test = "${list.size()> 0}">
<center><h2>Department List</h2></center>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>Budget</th>

</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>
<td>${dep.loc}</td>
<td>${dep.budget}</td>

</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

InsertForm.jsp Page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

Sensitivity: Internal & Restricted


<body>
<div class="container pt-3">
<form:form action="saveForm" modelAttribute="dept">
<div class="form-group">
<label for="dname">Department Name:</label>
<form:input path="dname" class="form-control"/>
</div>
<div class="form-group">
<label for="loc">Location:</label>
<form:input path="loc" class="form-control"/>
</div>
<div class="form-group">
<label for="loc">Budget:</label>
<form:input path="budget" class="form-control"/>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
</body>
</html>

ShowByName.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="byname">
Enter Department Name : <input type="text" name="txtDname"/>
<input type="submit">
</form>
<h2>Department List</h2>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Department Name</th>
<th>Location</th>
<th>budget</th>
</tr>
<c:forEach var="dep" items="${list}">
<tr>
<td>${dep.deptno}</td>
<td>${dep.dname}</td>

Sensitivity: Internal & Restricted


<td>${dep.loc}</td>
<td>${dep.budget}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

DeleteByName.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="deletebyname1">
Enter Department Name : <input type="text" name="txtDname"/>
<input type="submit">
</form>

</body>
</html>

ShowByBudget.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<form action="showByBudget">
Enter Department Name : <input type="text" name="txtBudget"/>
<input type="submit">
</form>

Sensitivity: Internal & Restricted


</body>
</html>

Output:

Click on insert

Click on Show by Name:

Sensitivity: Internal & Restricted


GO Back to main menu → Click on Order By Budget

GO Back to main menu → Click on show By budget

GO Back to main menu → Click on delete by Id

Sensitivity: Internal & Restricted


Sensitivity: Internal & Restricted

You might also like