Advanced Java
Anytime, anywhere
-Professor Shweta Waghmare
Module 6 : Getting Started with
Spring Boot
Topics in Module 6
❏ Spring Boot and Database
❏ Spring Boot Web Application Development
❏ Spring Boot RESTful WebServices
❏ Self learning topics: Understanding Transaction Management in Spring
Ref : https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-
reference/html/transaction.html#:~:text=The%20Spring%20Framework%20provides%20a,Java%20Data%
20Objects%20(JDO).
Spring Boot
Java Spring Framework (Spring Framework) is a popular, open source, enterprise-
level framework for creating standalone, production-grade applications that run on
the Java Virtual Machine (JVM).(regular and intensive use with real users)
Java Spring Boot (Spring Boot) is a tool that makes developing web application and
microservices with Spring Framework faster and easier through three core
capabilities:
1. Autoconfiguration
2. An opinionated approach to configuration
3. The ability to create standalone applications
These features work together to provide you with a tool that allows you to set up a
Spring-based application with minimal configuration and setup.
Why is Spring Framework so popular?(Just for ref)
Spring Framework offers a dependency injection feature that lets objects define their own
dependencies that the Spring container later injects into them. This enables developers
to create modular applications consisting of loosely coupled components that are ideal
for microservices and distributed network applications.
Spring Framework also offers built-in support for typical tasks that an application needs
to perform, such as data binding, type conversion, validation, exception handling,
resource and event management, internationalization, and more
In sum, Spring Framework provides developers with all the tools and features the
need to create loosely coupled, cross-platform Java EE applications that run in any
environment.
What is micro service?
Micro Service is an architecture that allows the developers to develop and
deploy services independently.
Each service running has its own process and this achieves the lightweight
model to support business applications.
Micro services offers the following advantages to its developers −
● Easy deployment
● Simple scalability
● Compatible with Containers
● Minimum configuration
● Lesser production time
What is spring boot?
Spring Boot provides a good platform for Java developers to develop a stand-
alone and production-grade spring application that you can just run. You can
get started with minimum configurations without the need for an entire Spring
configuration setup.
Advantages
Spring Boot offers the following advantages to its developers −
● Easy to understand and develop spring applications
● Increases productivity
● Reduces the development time
Spring boot goals-
Spring Boot is designed with the following goals −
● To avoid complex XML configuration in Spring
● To develop a production ready Spring applications in an easier way
● To reduce the development time and run the application independently
● Offer an easier way of getting started with the application
Why Spring Boot?
You can choose Spring Boot because of the features and benefits it offers as
given here −
● It provides a flexible way to configure Java Beans, XML configurations, and
Database Transactions.
● It provides a powerful batch processing and manages REST endpoints.
● In Spring Boot, everything is auto configured; no manual configurations are
needed.
● It offers annotation-based spring application
● Eases dependency management
● It includes Embedded Servlet Container
What Spring Boot adds to Spring Framework
Autoconfiguration
Autoconfiguration means that applications are initialized with pre-set dependencies that
you don't have to configure manually. As Java Spring Boot comes with built-in
autoconfiguration capabilities, it automatically configures both the underlying Spring
Framework and third-party packages based on your settings (and based on best
practices, which helps avoid errors).
Even though you can override these defaults once the initialization is complete, Java
Spring Boot's auto configuration feature enables you to start developing your Spring-
based applications fast and reduces the possibility of human errors.
What Spring Boot adds to Spring Framework
Opinionated approach
Spring Boot uses an opinionated approach to adding and configuring starter dependencies,
based on the needs of your project. Following its own judgment, Spring Boot chooses which
packages to install and which default values to use, rather than requiring you to make all those
decisions yourself and set up everything manually.
You can define the needs of your project during the initialization process, during which you
choose among multiple starter dependencies—called Spring Starters—that cover typical use
cases.
For example, the ‘Spring Web’ starter dependency allows you to build Spring-based web
applications with minimal configuration by adding all the necessary dependencies—such as
the Apache Tomcat web server—to your project.
‘Spring Security’ is another popular starter dependency that automatically adds authentication
and access-control features to your application.
Spring Boot includes over 50 Spring Starters, and many more third-party starters are available.
What Spring Boot adds to Spring Framework
Standalone applications
Spring Boot helps developers create applications that just run. Specifically, it lets you create
standalone applications that run on their own, without relying on an external web server, by
embedding a web server such as Tomcat or Netty into your app during the initialization
process.
As a result, you can launch your application on any platform by simply hitting the Run
command. (You can opt out of this feature to build applications without an embedded Web
server.)
How does it works?
Spring Boot automatically configures your application based on the dependencies
you have added to the project by using @EnableAutoConfiguration annotation. For
example, if MySQL database is on your classpath, but you have not configured any
database connection, then Spring Boot auto-configures an in-memory database.
The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.
Spring Boot automatically scans all the components included in the project by using
@ComponentScan annotation.(SpringApplication.class)
Spring Boot Starters
Handling dependency management is a difficult task for big projects. Spring
Boot resolves this problem by providing a set of dependencies for
developers convenience.
For example, if you want to use Spring and JPA for database access, it is
sufficient if you include spring-boot-starter-data-jpa dependency in your
project.
Note that all Spring Boot starters follow the same naming pattern spring-
boot-starter- *, where * indicates that it is a type of the application.
Spring Boot Starter Actuator dependency is used to monitor and manage your
application.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Spring Boot Starter Security dependency is used for Spring Security.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot Starter web dependency is used to write a Rest Endpoints.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Auto Configuration
Spring Boot Auto Configuration automatically configures your Spring application based on the JAR
dependencies you added in the project. For example, if MySQL database is on your class path, but
you have not configured any database connection, then Spring Boot auto configures an in-memory
database.
For this purpose, you need to add @EnableAutoConfiguration annotation or
@SpringBootApplication annotation to your main class file. Then, your Spring Boot application will
be automatically configured.
Spring Boot Application
The entry point of the Spring Boot Application is the class contains @SpringBootApplication
annotation. This class should have the main method to run the Spring Boot application.
@SpringBootApplication annotation includes Auto- Configuration, Component Scan, and
Spring Boot Configuration.
If you added @SpringBootApplication annotation to the class, you do not need to add the
@EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration
annotation. The @SpringBootApplication annotation includes all other annotations.
Component Scan
Spring Boot application scans all the beans and package declarations when the
application initializes. You need to add the @ComponentScan annotation for your
class file to scan your components added in your project.
Spring boot Annotations
Spring Boot Annotations is a form of metadata that provides data about a program.
In other words, annotations are used to provide supplemental information about a
program.
It is not a part of the application that we develop.
It does not have a direct effect on the operation of the code they annotate.
It does not change the action of the compiled program.
Core spring FW annotations
@Required: It applies to the bean setter method. It indicates that the annotated bean must
be populated at configuration time with the required property, else it throws an exception
BeanInitilizationException.
@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired
annotation. It is used to autowire spring bean on setter methods, instance variable, and
constructor. When we use @Autowired annotation, the spring container auto-wires the bean
by matching data-type.
@Configuration: It is a class-level annotation. The class annotated with @Configuration used
by Spring Containers as a source of bean definitions.
@ComponentScan: It is used when we want to scan a package for beans. It is used with the
annotation @Configuration. We can also specify the base packages to scan for Spring
Components.
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the
method to produce a bean to be managed by Spring Container.
Spring fw stereotype annotation
@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java
class annotated with @Component is found during the classpath. The Spring Framework
pick it up and configure it in the application context as a Spring Bean.
@Controller: The @Controller is a class-level annotation. It is a specialization of
@Component. It marks a class as a web request handler. It is often used to serve web
pages. By default, it returns a string that indicates which route to redirect. It is mostly used
with @RequestMapping annotation.
@Service: It is also used at class level. It tells the Spring that class contains the business
logic.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object)
that access the database directly. The repository does all the operations related to the
database.
Spring boot annotation
@EnableAutoConfiguration: It auto-configures the bean that is present in the classpath
and configures it to run the methods. The use of this annotation is reduced in Spring Boot
1.2.0 release because developers provided an alternative of the annotation, i.e.
@SpringBootApplication.
@SpringBootApplication: It is a combination of three annotations
@EnableAutoConfiguration, @ComponentScan, and @Configuration.
@RestController: The @RestController annotation from Spring Boot is basically a quick
shortcut that saves us from always having to define @ResponseBody.
Spring MVC and REST Annotation
@RequestMapping: It is used to map the web requests. It has many optional elements like
consumes, header, method, name, params, path, produces, and value. We use it with the class as
well as the method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a
web service endpoint that fetches It is used instead of using: @RequestMapping(method =
RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create
a web service endpoint that creates It is used instead of using: @RequestMapping(method =
RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a
web service endpoint that creates or updates It is used instead of using:
@RequestMapping(method = RequestMethod.PUT)
Spring Boot Architecture
Spring Boot follows a layered architecture in which each layer communicates with the layer
directly below or above (hierarchical structure) it.
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
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.
Spring Boot - SpringApplication Example
● SpringApplication#run SpringApplication.run(Classname.class, args)
bootstraps a spring application as a stand-alone application from the main
method.
● It creates an appropriate ApplicationContext instance and load beans.
● It also runs embedded Tomcat server in Spring web application
@SpringBootApplication
A single @SpringBootApplication annotation is used to enable the following annotations:
● @EnableAutoConfiguration: It enables the Spring Boot auto-configuration
mechanism.
● @ComponentScan: It scans the package where the application is located.
● @Configuration: It allows us to register extra beans in the context or import
additional configuration classes.
Internal working of Spring Boot
package com.exampleboot.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootExampleSts.class,
args);
}
}
Spring MVC the view tier
A Spring MVC is a Java framework which is used to build web applications. It follows
the Model-View-Controller design pattern. It implements all the basic features of a
core spring framework like Inversion of Control, Dependency Injection.
Ways to Create Spring Boot Project:
1. Create Maven project and add Starter Project
2. Use Spring Initializr : https://start.spring.io/
3. Use IDE like STS : https://spring.io/tools
4. Spring boot Command Line Interface
Prerequisite of Spring Boot
To create a Spring Boot application, following are the prerequisites. In this tutorial, we
will use Spring Tool Suite (STS) IDE.
● Java 1.8
● Maven 3.0+
● Spring Framework 5.0.0.BUILD-SNAPSHOT
● An IDE (Spring Tool Suite) is recommended.
Program :
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Write a Rest Endpoint
To write a simple Hello World Rest Endpoint in the Spring Boot Application main
class file itself, follow the steps shown below −
● Firstly, add the @RestController annotation at the top of the class.
● Now, write a Request URI method with @RequestMapping annotation.
● Then, the Request URI method should return the Hello World string.
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/")
public String hello() {
return "Hello World";
}
}
Right Click the project -> Maven -> Update Project
Then Re-run the project.
---------------------------------------------------------------------------
Main class is configurable in pom.xml
<properties> <start-class>com.bt.collab.alu.api.webapp.Application</start-class>
</properties>
If error
1.Installation of Spring Tools Through Eclipse MarketPlace
Write a program to create a simple Spring Boot application that prints a
message.
Step 1: New spring starter project File->New->Other->Spring->Spring Start
Project
Step 2: -Give Project Name->MVC_DEMO->Next button
Step 3: Add Spring starter project Dependencies
Select following dependencies:
1.Select Spring Boot Dev Tools(this tools helps in quick deployment of
change without restart of the server or container
2. Select thymleaf: This component is used for view component
deployment For view component deployment MVC Consist of model view
controller. This helps us to have view component development
3. Select Spring web: It is required dependency for web application
development which build web including restful applications using spring
mvc and it has an embedded tomcat server in it.
Step 4: Click on next -> click on finish
Step 5:Check pom.xml file In pom.xml -> Check the dependencies spring
bootstarter,web dev tools,thymleaf
Step 6: Check the main the application file which main entry point of spring
boot application is scr->package-> demoApplication
1. Springboot application annotation and main method
2. SpringApplication.run(Assignment101Application.class, args);
Above line 2 is default created whenever we create the project
Step 7:Run this application->spring boot app->
Step 9: Create html file in template folder
Spring Boot – Application Properties
In Spring Boot, whenever you create a new
Spring Boot Application in spring starter, or
inside an IDE (Eclipse or STS) a file is
located inside the src/main/resources
folder named as application.properties file
which is shown in the below image as
shown below as follows:
in a spring boot application, application.properties file is used to write the
application-related property into that file. This file contains the different
configuration which is required to run the application in a different environment, and
each environment will have a different property defined by it.
Inside the application properties file, we define every type of property like changing
the port, database connectivity, connection to the eureka server, and many more.
● Example 1: To Change the Port Number : server.port=8989
● Example 2: To define the name of our application : spring.application.name =
userservice
● Example 3: Connecting with the MySQL Database
To connect with the MySQL Database you have to write a bunch of lines. You can
write the properties like this
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
Spring boot and database
Working with SQL Databases :
The Spring Framework provides extensive support for working with SQL
databases, from direct JDBC access using JdbcTemplate to complete
“object relational mapping” technologies such as Hibernate.
Spring Data provides an additional level of functionality: creating
Repository implementations directly from interfaces and using
conventions to generate queries from your method names.
Example : https://hevodata.com/learn/spring-boot-mysql/
Spring boot and database
How to configure and write code for connecting to a PostgreSQL database
In a Spring Boot application, the two common ways:
● Use Spring JDBC with JdbcTemplate to connect to a PostgreSQL database
● Use Spring Data JPA to connect to a PostgreSQL database
To connect a Spring Boot application to a PostgreSQL database, you need follow these
steps below:
● Add a dependency for PostgreSQL JDBC driver, which is required to allow Java
applications to be able to talk with a PostgreSQL database server.
● Configure data source properties for the database connection information
● Add a dependency for Spring JDBC or Spring Data JPA, depending on your need:
○ Use Spring JDBC for executing plain SQL statements
○ Use Spring Data JPA for more advanced use, e.g. mapping Java classes to
tables and Java objects to rows, and take advantages of the Spring Data
JPA API.
1. Add dependency for PostgreSQL JDBC Driver
Declare the following dependency in your project’s pom.xml file:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
2. Configure Data Source Properties
Next, you need to specify some database connection information in the Spring Boot
application configuration file (application.properties) as
follows:(src/main/resources/application.properties)
spring.datasource.url=jdbc:postgresql://localhost:5432/shopme
spring.datasource.username=postgres
spring.datasource.password=password
Here, the JDBC URL points to a PostgreSQL database server running on localhost.
Update the JDBC URL, username and password according to your environment.
3. Connect to PostgreSQL Database with Spring JDBC
In the simplest case, you can use Spring JDBC with JdbcTemplate to work
with a relational database. So add the following dependency to your Maven
project file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
4. Connect to PostgreSQL Database with Spring Data JPA
If you want to map Java classes to tables and Java objects to rows and take
advantages of an Object-Relational Mapping (ORM) framework like Hibernate,
you can use Spring Data JPA. So declare the following dependency to your
project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Besides the JDBC URL, username and password, you can also specify some additional properties
as follows:()
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
Spring Boot CRUD Operations
What is the CRUD operation?
The CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic
functions of the persistence storage.
The CRUD operation can be defined as user interface conventions that allow view, search, and
modify information through computer-based forms and reports. CRUD is data-oriented and the
standardized use of HTTP action verbs. HTTP has a few important verbs.
● POST: Creates a new resource
● GET: Reads a resource
● PUT: Updates an existing resource
● DELETE: Deletes a resource
The CRUD operations refer to all major functions that are implemented in relational
database applications. Each letter of the CRUD can map to a SQL statement and HTTP
methods.
Spring Boot JpaRepository
JpaRepository provides JPA related methods such as flushing, persistence context,
and deletes a record in a batch.
It is defined in the package org.springframework.data.jpa.repository.
JpaRepository extends both CrudRepository and PagingAndSortingRepository.
For example:
public interface BookDAO extends JpaRepository
{
}
Step 1: Open Spring Initializr http://start.spring.io.
Step 2: Select the Spring Boot version 2.3.0.M1.
Step 2: Provide the Group name. We have provided com.javatpoint.
Step 3: Provide the Artifact Id. We have provided spring-boot-crud-operation.
Step 4: Add the dependencies Spring Web, Spring Data JPA, and H2
Database.
Step 5: Click on the Generate button. When we click on the Generate button, it
wraps the specifications in a Jar file and downloads it to the local system.
Step 6: Extract the Jar file and paste it into the STS workspace.
Step 7: Import the project folder into STS.
File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-crud-
operation -> Finish
It takes some time to import.
Step 8: Create a package with the name com.javatpoint.model in the folder src/main/java.
Step 10: Create a model class in the package com.javatpoint.model. We have created a
model class with the name Books. In the Books class, we have done the following:
● Define four variable bookid, bookname, author, and
● Generate Getters and Setters.
Right-click on the file -> Source -> Generate Getters and Setters.
● Mark the class as an Entity by using the annotation @Entity.
● Mark the class as Table name by using the annotation @Table.
● Define each variable as Column by using the annotation @Column.
@Entity
//defining class name as Table name
@Table
public class Books
{
//Defining book id as primary key
@Id
@Column
private int bookid;
@Column
private String bookname;
@Column
private String author;
@Column
private int price;
public int getBookid()
{ return bookid; }
public void setBookid(int bookid)
{ this.bookid = bookid; }
public String getBookname()
{ return bookname; }
public void setBookname(String bookname)
{ this.bookname = bookname; }
public String getAuthor()
{ return author; }
public void setAuthor(String author)
{ this.author = author; }
public int getPrice()
{ return price; }
public void setPrice(int price)
{ this.price = price; }
}
BooksController.java
@RestController
public class BooksController
{
@Autowired
BooksService booksService;
@GetMapping("/book")
private List<Books> getAllBooks()
{
return booksService.getAllBooks();
}
@GetMapping("/book/{bookid}")
private Books getBooks(@PathVariable("bookid") int bookid)
{
return booksService.getBooksById(bookid);
}
@DeleteMapping("/book/{bookid}")
private void deleteBook(@PathVariable("bookid") int bookid)
{
booksService.delete(bookid);
}
@PostMapping("/books")
private int saveBook(@RequestBody Books books)
{
booksService.saveOrUpdate(books);
return books.getBookid();
}
@PutMapping("/books")
private Books update(@RequestBody Books books)
{
booksService.saveOrUpdate(books);
return books;
}
}
BooksService.java
@Service
public class BooksService
{ @Autowired
BooksRepository booksRepository;
public List<Books> getAllBooks()
{ List<Books> books = new ArrayList<Books>();
booksRepository.findAll().forEach(books1 -> books.add(books1));
return books;
}
public Books getBooksById(int id)
{ return booksRepository.findById(id).get(); }
public void saveOrUpdate(Books books)
{ booksRepository.save(books); }
public void delete(int id)
{ booksRepository.deleteById(id); }
public void update(Books books, int bookid)
{ booksRepository.save(books); }
}
Step 10: Create a Repository interface. We have created a repository interface with the
name BooksRepository in the package com.javatpoint.repository. It extends the Crud
Repository interface.
BooksRepository.java
package com.javatpoint.repository;
import org.springframework.data.repository.CrudRepository;
import com.javatpoint.model.Books;
//repository that extends CrudRepository
public interface BooksRepository extends CrudRepository<Books, Integer>
{ }
Step 11: Open the application.properties file and configure the following properties.
application.properties
spring.datasource.url=jdbc:h2:mem:books_data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sam
spring.datasource.password=sam
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enabling the H2 console
spring.h2.console.enabled=true
Another Example : And you need to code an entity class (a POJO Java class) to map with
the corresponding table in the database, as follows:
package net.codejava;
import javax.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String email;
// getters and setters…
}
Then you need to declare a repository interface as follows:
Declare repository interface for our entity. This interface will act as a bridge
between the Java class and the actual table in the database.
package net.codejava;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student,
Integer> {
}
And then you can use this repository in a Spring MVC controller or business class as
follows
@Controller
public class StudentController {//business logic
@Autowired
private StudentRepository studentRepo;
@GetMapping("/students")
public String listAll(Model model) {
List<Student> listStudents = studentRepo.findAll();
model.addAttribute("listStudents", listStudents);
return "students";
}
}
Spring Boot with spring data JPA
JPa Repository
JpaRepository is JPA specific extension of Repository. It contains the full API of
CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD
operations and also API for pagination and sorting.
Note: Command Line Runner is an interface. It is used to execute the code after the
Spring Boot application started.
Spring Boot JPA
What is JPA?
● Spring Boot JPA is a Java specification for managing relational data in Java
applications. It allows us to access and persist data between Java object/ class and
relational database.
● JPA follows Object-Relation Mapping (ORM). It is a set of interfaces.
● It also provides a runtime EntityManager API for processing queries and transactions
on the objects against the database.
● It uses a platform-independent object-oriented query language JPQL (Java Persistent
Query Language).
In the context of persistence, it covers three areas:
● The Java Persistence API
● Object-Relational metadata
● The API itself, defined in the persistence package
JPA is not a framework. It defines a concept that can be implemented by any framework.
Why should we use JPA?
JPA is simpler, cleaner, and less labor-intensive than JDBC, SQL, and handwritten mapping. JPA is
suitable for non-performance oriented complex applications. The main advantage of JPA over JDBC
is that, in JPA, data is represented by objects and classes while in JDBC data is represented by
tables and records. It uses POJO to represent persistent data that simplifies database
programming.
There are some other advantages of JPA:
● JPA avoids writing DDL in a database-specific dialect of SQL. Instead of this, it allows mapping
in XML or using Java annotations.
● JPA allows us to avoid writing DML in the database-specific dialect of SQL.
● JPA allows us to save and load Java objects and graphs without any DML language at all.
● When we need to perform queries JPQL, it allows us to express the queries in terms of Java
entities rather than the (native) SQL table and columns.
JPA Features
● It is a powerful repository and custom object-mapping abstraction.
● It supports for cross-store persistence. It means an entity can be partially stored in
MySQL and Neo4j (Graph Database Management System).
● It dynamically generates queries from queries methods name.
● The domain base classes provide basic properties.
● It supports transparent auditing.
● Possibility to integrate custom repository code.
● It is easy to integrate with Spring Framework with the custom namespace.
JPA Architecture
JPA is a source to store
business entities as
relational entities. It shows
how to define a POJO as an
entity and how to manage
entities with relation.
JPA Architecture
● Persistence: It is a class that contains static methods to obtain an
EntityManagerFactory instance.
● EntityManagerFactory: It is a factory class of EntityManager. It creates and
manages multiple instances of EntityManager.
● EntityManager: It is an interface. It controls the persistence operations on
objects. It works for the Query instance.
● Entity: The entities are the persistence objects stores as a record in the database.
● Persistence Unit: It defines a set of all entity classes. In an application,
EntityManager instances manage it. The set of entity classes represents the data
contained within a single data store.
● EntityTransaction: It has a one-to-one relationship with the EntityManager class.
For each EntityManager, operations are maintained by EntityTransaction class.
● Query: It is an interface that is implemented by each JPA vendor to obtain
relation objects that meet the criteria.
JPA Class Relationships
● The relationship between EntityManager and EntiyTransaction is one-to-one. There is an
EntityTransaction instance for each EntityManager operation.
● The relationship between EntityManageFactory and EntiyManager is one-to-many. It is a
factory class to EntityManager instance.
● The relationship between EntityManager and Query is one-to-many. We can execute any
number of queries by using an instance of EntityManager class.
● The relationship between EntityManager and Entity is one-to-many. An EntityManager
instance can manage multiple Entities.
JPA Class Relationships
What is web service?
• A web service is a set of open protocols and standards that allow data to be
exchanged between different applications or systems.
• Web services can be used by software programs written in a variety of programming
languages and running on a variety of platforms to exchange data via computer
networks such as the Internet in a similar way to inter-process communication on a
single computer.
• Any software, application, or cloud technology that uses standardized web protocols
(HTTP or HTTPS) to connect, interoperate, and exchange data messages –
commonly XML (Extensible Markup Language) – across the internet is considered a
web service.
What is a REST API?
● An API, or application programming interface, is a set of rules that define how
applications or devices can connect to and communicate with each other.
● A REST API is an API that conforms to the design principles of the REST, or
representational state transfer architectural style. For this reason, REST APIs are
sometimes referred to RESTful APIs.
● A REST API is designed to provide a lightweight form of communication (less
bandwidth) between producer (ex: Twitter) and consumer (ex: Twitter client)
● REST APIs provide a flexible, lightweight way to integrate applications, and have
emerged as the most common method for connecting components in
microservices architectures.
How REST APIs work
REST APIs communicate via HTTP requests to perform standard database functions like creating,
reading, updating, and deleting records (also known as CRUD) within a resource.
For example, a REST API would use a GET request to retrieve a record, a POST request to create
one, a PUT request to update a record, and a DELETE request to delete one.
All HTTP methods can be used in API calls.
A well-designed REST API is similar to a website running in a web browser with built-in HTTP
functionality.
The state of a resource at any particular instant, or timestamp, is known as the resource
representation. This information can be delivered to a client in virtually any format including
JavaScript Object Notation (JSON), HTML, XLT, Python, PHP, or plain text.
Request headers and parameters are also important in REST API calls because they include
important identifier information such as metadata, authorizations, uniform resource identifiers
(URIs), caching,cookies and more. Along with conventional HTTP status codes, are used within
well-designed REST APIs.
RESTful API is an application program
interface (API) that uses HTTP requests to
GET, PUT, POST and DELETE data
Write a program to demonstrate RESTful Web Services with spring boot.(Product
Application)
Download and Install Postman: www.postman.com
Refer :
https://docs.google.com/document/d/13mwTBiMPDGnL_PHa3UrkuCS6VqfO
pJoF6hL-7KPgwb8/edit?usp=sharing
Introduction to RESTful Web Services
REST stands for REpresentational State Transfer.
It is developed by Roy Thomas Fielding, who also developed HTTP.
The main goal of RESTful web services is to make web services more effective.
RESTful web services try to define services using the different concepts that are already
present in HTTP. REST is an architectural approach, not a protocol.
It does not define the standard message exchange format. We can build REST services with
both XML and JSON. JSON is more popular format with REST.
The key abstraction is a resource in REST. A resource can be anything. It can be accessed
through a Uniform Resource Identifier (URI).
Introduction to RESTful Web Services
The resource has representations like XML, HTML, and JSON. The current state capture by
representational resource. When we request a resource, we provide the representation of the
resource. The important methods of HTTP are:
● GET: It reads a resource.
● PUT: It updates an existing resource.
● POST: It creates a new resource.
● DELETE: It deletes the resource.
EXAMPLE :
POST /users: It creates a user.
GET /users/{id}: It retrieves the detail of a user.
GET /users: It retrieves the detail of all users.
DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
GET /users/{id}/posts/post_id: It retrieve the detail
of a specific post.
POST / users/{id}/ posts: It creates a post of the
user.
Spring Boot - Building RESTful Web Services
Spring Boot provides a very good support to building RESTful Web Services for enterprise
applications. This chapter will explain in detail about building RESTful web services using Spring
Boot.
Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web
dependency into the build configuration file.
If you are a Maven user, use the following code to add the below dependency in your pom.xml file
−
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If you are a Gradle user, use the following code to add the below dependency in your build.gradle
file. compile('org.springframework.boot:spring-boot-starter-web')
Spring Boot - Building RESTful Web Services
Rest Controller
The @RestController annotation is used to define the RESTful web services.
It serves JSON, XML and custom response.
Its syntax is shown below −
@RestController
public class ProductServiceController {
}
Spring Boot - Building RESTful Web Services
Request Mapping
The @RequestMapping annotation is used to define the Request URI to access the REST
Endpoints. We can define Request method to consume and produce object. The default request
method is GET.
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() { }
@GetMapping is a composed annotation that acts as a shortcut for
@RequestMapping(method = RequestMethod.GET).
We can apply @GetMapping only on method level and @RequestMapping annotation can be
applied on class level and as well as on method level.
@GetMapping is the newer annotaion.
Spring Boot restful Web services
Request Body
The @RequestBody annotation is used to define the request body content type.
//create new service=@RequestBody
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
}
Spring Boot restful Web services
Path Variable
The @PathVariable annotation is used to define the custom or dynamic request URI.
The Path variable in request URI is defined as curly braces {} as shown below −
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) {
//update
//delete
}
Spring Boot restful Web services
Request Parameter
The @RequestParam annotation is used to read the request parameters from the Request
URL. By default, it is a required parameter. We can also set default value for request
parameters as shown here −
public ResponseEntity<Object> getProduct(
@RequestParam(value = "name", required = false, defaultValue = "honey") String name) {
}
Get API(Read operation)
The default HTTP request method is GET.
This method does not require any Request Body.
You can send request parameters and path variables to define the custom or dynamic URL.
Post API(Create Operation)
The HTTP POST request is used to create a resource.
This method contains the Request Body.
We can send request parameters and path variables to define the custom or dynamic URL.
Put API
The HTTP PUT request is used to update the existing resource
This method contains a Request Body.
We can send request parameters and path variables to define the custom or dynamic URL.
Delete API
The HTTP Delete request is used to delete the existing resource.
This method does not contain any Request Body.
We can send request parameters and path variables to define the custom or dynamic URL.
Spring Boot - Building RESTful Web Services
The Spring Boot main application class – DemoApplication.java
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
The POJO class – Product.java
package com.tutorialspoint.demo.model;
public class Product {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The Rest Controller class – ProductServiceController.java
package com.tutorialspoint.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.model.Product;
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Object> delete(@PathVariable("id") String id) {
productRepo.remove(id);
return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
//update or create
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id,
@RequestBody Product product)
{
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK);
}
@RequestMapping(value = "/products", method = RequestMethod.POST)
public ResponseEntity<Object> createProduct(@RequestBody Product product) {
productRepo.put(product.getId(), product);
return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProduct() {
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
GET API URL is: http://localhost:8080/products
POST API URL is: http://localhost:8080/products
PUT API URL is: http://localhost:8080/products/3
DELETE API URL is: http://localhost:8080/products/3

Module 6 _ Spring Boot for java application to begin

  • 1.
  • 2.
    Module 6 :Getting Started with Spring Boot
  • 3.
    Topics in Module6 ❏ Spring Boot and Database ❏ Spring Boot Web Application Development ❏ Spring Boot RESTful WebServices ❏ Self learning topics: Understanding Transaction Management in Spring Ref : https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework- reference/html/transaction.html#:~:text=The%20Spring%20Framework%20provides%20a,Java%20Data% 20Objects%20(JDO).
  • 5.
    Spring Boot Java SpringFramework (Spring Framework) is a popular, open source, enterprise- level framework for creating standalone, production-grade applications that run on the Java Virtual Machine (JVM).(regular and intensive use with real users) Java Spring Boot (Spring Boot) is a tool that makes developing web application and microservices with Spring Framework faster and easier through three core capabilities: 1. Autoconfiguration 2. An opinionated approach to configuration 3. The ability to create standalone applications These features work together to provide you with a tool that allows you to set up a Spring-based application with minimal configuration and setup.
  • 7.
    Why is SpringFramework so popular?(Just for ref) Spring Framework offers a dependency injection feature that lets objects define their own dependencies that the Spring container later injects into them. This enables developers to create modular applications consisting of loosely coupled components that are ideal for microservices and distributed network applications. Spring Framework also offers built-in support for typical tasks that an application needs to perform, such as data binding, type conversion, validation, exception handling, resource and event management, internationalization, and more In sum, Spring Framework provides developers with all the tools and features the need to create loosely coupled, cross-platform Java EE applications that run in any environment.
  • 8.
    What is microservice? Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications. Micro services offers the following advantages to its developers − ● Easy deployment ● Simple scalability ● Compatible with Containers ● Minimum configuration ● Lesser production time
  • 9.
    What is springboot? Spring Boot provides a good platform for Java developers to develop a stand- alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. Advantages Spring Boot offers the following advantages to its developers − ● Easy to understand and develop spring applications ● Increases productivity ● Reduces the development time
  • 10.
    Spring boot goals- SpringBoot is designed with the following goals − ● To avoid complex XML configuration in Spring ● To develop a production ready Spring applications in an easier way ● To reduce the development time and run the application independently ● Offer an easier way of getting started with the application
  • 11.
    Why Spring Boot? Youcan choose Spring Boot because of the features and benefits it offers as given here − ● It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. ● It provides a powerful batch processing and manages REST endpoints. ● In Spring Boot, everything is auto configured; no manual configurations are needed. ● It offers annotation-based spring application ● Eases dependency management ● It includes Embedded Servlet Container
  • 12.
    What Spring Bootadds to Spring Framework Autoconfiguration Autoconfiguration means that applications are initialized with pre-set dependencies that you don't have to configure manually. As Java Spring Boot comes with built-in autoconfiguration capabilities, it automatically configures both the underlying Spring Framework and third-party packages based on your settings (and based on best practices, which helps avoid errors). Even though you can override these defaults once the initialization is complete, Java Spring Boot's auto configuration feature enables you to start developing your Spring- based applications fast and reduces the possibility of human errors.
  • 13.
    What Spring Bootadds to Spring Framework Opinionated approach Spring Boot uses an opinionated approach to adding and configuring starter dependencies, based on the needs of your project. Following its own judgment, Spring Boot chooses which packages to install and which default values to use, rather than requiring you to make all those decisions yourself and set up everything manually. You can define the needs of your project during the initialization process, during which you choose among multiple starter dependencies—called Spring Starters—that cover typical use cases. For example, the ‘Spring Web’ starter dependency allows you to build Spring-based web applications with minimal configuration by adding all the necessary dependencies—such as the Apache Tomcat web server—to your project. ‘Spring Security’ is another popular starter dependency that automatically adds authentication and access-control features to your application. Spring Boot includes over 50 Spring Starters, and many more third-party starters are available.
  • 14.
    What Spring Bootadds to Spring Framework Standalone applications Spring Boot helps developers create applications that just run. Specifically, it lets you create standalone applications that run on their own, without relying on an external web server, by embedding a web server such as Tomcat or Netty into your app during the initialization process. As a result, you can launch your application on any platform by simply hitting the Run command. (You can opt out of this feature to build applications without an embedded Web server.)
  • 15.
    How does itworks? Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database. The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method. Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation.(SpringApplication.class)
  • 16.
    Spring Boot Starters Handlingdependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience. For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project. Note that all Spring Boot starters follow the same naming pattern spring- boot-starter- *, where * indicates that it is a type of the application.
  • 17.
    Spring Boot StarterActuator dependency is used to monitor and manage your application. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Spring Boot Starter Security dependency is used for Spring Security. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot Starter web dependency is used to write a Rest Endpoints. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  • 18.
    Auto Configuration Spring BootAuto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured.
  • 19.
    Spring Boot Application Theentry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations.
  • 20.
    Component Scan Spring Bootapplication scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project.
  • 21.
    Spring boot Annotations SpringBoot Annotations is a form of metadata that provides data about a program. In other words, annotations are used to provide supplemental information about a program. It is not a part of the application that we develop. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.
  • 22.
    Core spring FWannotations @Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at configuration time with the required property, else it throws an exception BeanInitilizationException. @Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching data-type. @Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions. @ComponentScan: It is used when we want to scan a package for beans. It is used with the annotation @Configuration. We can also specify the base packages to scan for Spring Components. @Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be managed by Spring Container.
  • 23.
    Spring fw stereotypeannotation @Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated with @Component is found during the classpath. The Spring Framework pick it up and configure it in the application context as a Spring Bean. @Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation. @Service: It is also used at class level. It tells the Spring that class contains the business logic. @Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database directly. The repository does all the operations related to the database.
  • 24.
    Spring boot annotation @EnableAutoConfiguration:It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication. @SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration. @RestController: The @RestController annotation from Spring Boot is basically a quick shortcut that saves us from always having to define @ResponseBody.
  • 25.
    Spring MVC andREST Annotation @RequestMapping: It is used to map the web requests. It has many optional elements like consumes, header, method, name, params, path, produces, and value. We use it with the class as well as the method. @GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint that fetches It is used instead of using: @RequestMapping(method = RequestMethod.GET) @PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service endpoint that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST) @PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint that creates or updates It is used instead of using: @RequestMapping(method = RequestMethod.PUT)
  • 26.
    Spring Boot Architecture SpringBoot follows a layered architecture in which each layer communicates with the layer directly below or above (hierarchical structure) it. 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
  • 27.
    Presentation Layer: Thepresentation 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.
  • 29.
    Spring Boot -SpringApplication Example ● SpringApplication#run SpringApplication.run(Classname.class, args) bootstraps a spring application as a stand-alone application from the main method. ● It creates an appropriate ApplicationContext instance and load beans. ● It also runs embedded Tomcat server in Spring web application
  • 30.
    @SpringBootApplication A single @SpringBootApplicationannotation is used to enable the following annotations: ● @EnableAutoConfiguration: It enables the Spring Boot auto-configuration mechanism. ● @ComponentScan: It scans the package where the application is located. ● @Configuration: It allows us to register extra beans in the context or import additional configuration classes.
  • 31.
  • 32.
    package com.exampleboot.spring; import org.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootExampleSts.class, args); } }
  • 33.
    Spring MVC theview tier A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.
  • 34.
    Ways to CreateSpring Boot Project: 1. Create Maven project and add Starter Project 2. Use Spring Initializr : https://start.spring.io/ 3. Use IDE like STS : https://spring.io/tools 4. Spring boot Command Line Interface
  • 35.
    Prerequisite of SpringBoot To create a Spring Boot application, following are the prerequisites. In this tutorial, we will use Spring Tool Suite (STS) IDE. ● Java 1.8 ● Maven 3.0+ ● Spring Framework 5.0.0.BUILD-SNAPSHOT ● An IDE (Spring Tool Suite) is recommended.
  • 36.
    Program : package com.tutorialspoint.demo; importorg.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
  • 37.
    Write a RestEndpoint To write a simple Hello World Rest Endpoint in the Spring Boot Application main class file itself, follow the steps shown below − ● Firstly, add the @RestController annotation at the top of the class. ● Now, write a Request URI method with @RequestMapping annotation. ● Then, the Request URI method should return the Hello World string.
  • 38.
    package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping(value = "/") public String hello() { return "Hello World"; } }
  • 39.
    Right Click theproject -> Maven -> Update Project Then Re-run the project. --------------------------------------------------------------------------- Main class is configurable in pom.xml <properties> <start-class>com.bt.collab.alu.api.webapp.Application</start-class> </properties> If error
  • 40.
    1.Installation of SpringTools Through Eclipse MarketPlace
  • 42.
    Write a programto create a simple Spring Boot application that prints a message. Step 1: New spring starter project File->New->Other->Spring->Spring Start Project
  • 43.
    Step 2: -GiveProject Name->MVC_DEMO->Next button Step 3: Add Spring starter project Dependencies
  • 44.
    Select following dependencies: 1.SelectSpring Boot Dev Tools(this tools helps in quick deployment of change without restart of the server or container 2. Select thymleaf: This component is used for view component deployment For view component deployment MVC Consist of model view controller. This helps us to have view component development 3. Select Spring web: It is required dependency for web application development which build web including restful applications using spring mvc and it has an embedded tomcat server in it.
  • 45.
    Step 4: Clickon next -> click on finish Step 5:Check pom.xml file In pom.xml -> Check the dependencies spring bootstarter,web dev tools,thymleaf
  • 46.
    Step 6: Checkthe main the application file which main entry point of spring boot application is scr->package-> demoApplication 1. Springboot application annotation and main method 2. SpringApplication.run(Assignment101Application.class, args); Above line 2 is default created whenever we create the project Step 7:Run this application->spring boot app->
  • 49.
    Step 9: Createhtml file in template folder
  • 51.
    Spring Boot –Application Properties In Spring Boot, whenever you create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below image as shown below as follows:
  • 52.
    in a springboot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. ● Example 1: To Change the Port Number : server.port=8989 ● Example 2: To define the name of our application : spring.application.name = userservice ● Example 3: Connecting with the MySQL Database To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example spring.datasource.username=springuser spring.datasource.password=ThePassword spring.datasource.driver-class-name =com.mysql.jdbc.Driver
  • 53.
    Spring boot anddatabase Working with SQL Databases : The Spring Framework provides extensive support for working with SQL databases, from direct JDBC access using JdbcTemplate to complete “object relational mapping” technologies such as Hibernate. Spring Data provides an additional level of functionality: creating Repository implementations directly from interfaces and using conventions to generate queries from your method names. Example : https://hevodata.com/learn/spring-boot-mysql/
  • 54.
  • 55.
    How to configureand write code for connecting to a PostgreSQL database In a Spring Boot application, the two common ways: ● Use Spring JDBC with JdbcTemplate to connect to a PostgreSQL database ● Use Spring Data JPA to connect to a PostgreSQL database To connect a Spring Boot application to a PostgreSQL database, you need follow these steps below: ● Add a dependency for PostgreSQL JDBC driver, which is required to allow Java applications to be able to talk with a PostgreSQL database server. ● Configure data source properties for the database connection information ● Add a dependency for Spring JDBC or Spring Data JPA, depending on your need: ○ Use Spring JDBC for executing plain SQL statements ○ Use Spring Data JPA for more advanced use, e.g. mapping Java classes to tables and Java objects to rows, and take advantages of the Spring Data JPA API.
  • 56.
    1. Add dependencyfor PostgreSQL JDBC Driver Declare the following dependency in your project’s pom.xml file: <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
  • 57.
    2. Configure DataSource Properties Next, you need to specify some database connection information in the Spring Boot application configuration file (application.properties) as follows:(src/main/resources/application.properties) spring.datasource.url=jdbc:postgresql://localhost:5432/shopme spring.datasource.username=postgres spring.datasource.password=password Here, the JDBC URL points to a PostgreSQL database server running on localhost. Update the JDBC URL, username and password according to your environment.
  • 58.
    3. Connect toPostgreSQL Database with Spring JDBC In the simplest case, you can use Spring JDBC with JdbcTemplate to work with a relational database. So add the following dependency to your Maven project file: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
  • 60.
    4. Connect toPostgreSQL Database with Spring Data JPA If you want to map Java classes to tables and Java objects to rows and take advantages of an Object-Relational Mapping (ORM) framework like Hibernate, you can use Spring Data JPA. So declare the following dependency to your project: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> Besides the JDBC URL, username and password, you can also specify some additional properties as follows:() spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
  • 61.
    Spring Boot CRUDOperations What is the CRUD operation? The CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic functions of the persistence storage. The CRUD operation can be defined as user interface conventions that allow view, search, and modify information through computer-based forms and reports. CRUD is data-oriented and the standardized use of HTTP action verbs. HTTP has a few important verbs. ● POST: Creates a new resource ● GET: Reads a resource ● PUT: Updates an existing resource ● DELETE: Deletes a resource
  • 62.
    The CRUD operationsrefer to all major functions that are implemented in relational database applications. Each letter of the CRUD can map to a SQL statement and HTTP methods.
  • 63.
    Spring Boot JpaRepository JpaRepositoryprovides JPA related methods such as flushing, persistence context, and deletes a record in a batch. It is defined in the package org.springframework.data.jpa.repository. JpaRepository extends both CrudRepository and PagingAndSortingRepository. For example: public interface BookDAO extends JpaRepository { }
  • 65.
    Step 1: OpenSpring Initializr http://start.spring.io. Step 2: Select the Spring Boot version 2.3.0.M1. Step 2: Provide the Group name. We have provided com.javatpoint. Step 3: Provide the Artifact Id. We have provided spring-boot-crud-operation. Step 4: Add the dependencies Spring Web, Spring Data JPA, and H2 Database. Step 5: Click on the Generate button. When we click on the Generate button, it wraps the specifications in a Jar file and downloads it to the local system.
  • 67.
    Step 6: Extractthe Jar file and paste it into the STS workspace. Step 7: Import the project folder into STS. File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-crud- operation -> Finish It takes some time to import. Step 8: Create a package with the name com.javatpoint.model in the folder src/main/java. Step 10: Create a model class in the package com.javatpoint.model. We have created a model class with the name Books. In the Books class, we have done the following: ● Define four variable bookid, bookname, author, and ● Generate Getters and Setters. Right-click on the file -> Source -> Generate Getters and Setters. ● Mark the class as an Entity by using the annotation @Entity. ● Mark the class as Table name by using the annotation @Table. ● Define each variable as Column by using the annotation @Column.
  • 68.
    @Entity //defining class nameas Table name @Table public class Books { //Defining book id as primary key @Id @Column private int bookid; @Column private String bookname; @Column private String author; @Column private int price; public int getBookid() { return bookid; } public void setBookid(int bookid) { this.bookid = bookid; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
  • 69.
    BooksController.java @RestController public class BooksController { @Autowired BooksServicebooksService; @GetMapping("/book") private List<Books> getAllBooks() { return booksService.getAllBooks(); } @GetMapping("/book/{bookid}") private Books getBooks(@PathVariable("bookid") int bookid) { return booksService.getBooksById(bookid); }
  • 70.
    @DeleteMapping("/book/{bookid}") private void deleteBook(@PathVariable("bookid")int bookid) { booksService.delete(bookid); } @PostMapping("/books") private int saveBook(@RequestBody Books books) { booksService.saveOrUpdate(books); return books.getBookid(); } @PutMapping("/books") private Books update(@RequestBody Books books) { booksService.saveOrUpdate(books); return books; } }
  • 71.
    BooksService.java @Service public class BooksService {@Autowired BooksRepository booksRepository; public List<Books> getAllBooks() { List<Books> books = new ArrayList<Books>(); booksRepository.findAll().forEach(books1 -> books.add(books1)); return books; } public Books getBooksById(int id) { return booksRepository.findById(id).get(); } public void saveOrUpdate(Books books) { booksRepository.save(books); } public void delete(int id) { booksRepository.deleteById(id); } public void update(Books books, int bookid) { booksRepository.save(books); } }
  • 72.
    Step 10: Createa Repository interface. We have created a repository interface with the name BooksRepository in the package com.javatpoint.repository. It extends the Crud Repository interface. BooksRepository.java package com.javatpoint.repository; import org.springframework.data.repository.CrudRepository; import com.javatpoint.model.Books; //repository that extends CrudRepository public interface BooksRepository extends CrudRepository<Books, Integer> { }
  • 73.
    Step 11: Openthe application.properties file and configure the following properties. application.properties spring.datasource.url=jdbc:h2:mem:books_data spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sam spring.datasource.password=sam spring.jpa.database-platform=org.hibernate.dialect.H2Dialect #enabling the H2 console spring.h2.console.enabled=true
  • 74.
    Another Example :And you need to code an entity class (a POJO Java class) to map with the corresponding table in the database, as follows: package net.codejava; import javax.persistence.*; @Entity @Table(name = "students") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String email; // getters and setters… }
  • 75.
    Then you needto declare a repository interface as follows: Declare repository interface for our entity. This interface will act as a bridge between the Java class and the actual table in the database. package net.codejava; import org.springframework.data.jpa.repository.JpaRepository; public interface StudentRepository extends JpaRepository<Student, Integer> { }
  • 76.
    And then youcan use this repository in a Spring MVC controller or business class as follows @Controller public class StudentController {//business logic @Autowired private StudentRepository studentRepo; @GetMapping("/students") public String listAll(Model model) { List<Student> listStudents = studentRepo.findAll(); model.addAttribute("listStudents", listStudents); return "students"; } }
  • 77.
    Spring Boot withspring data JPA JPa Repository JpaRepository is JPA specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. Note: Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started.
  • 78.
    Spring Boot JPA Whatis JPA? ● Spring Boot JPA is a Java specification for managing relational data in Java applications. It allows us to access and persist data between Java object/ class and relational database. ● JPA follows Object-Relation Mapping (ORM). It is a set of interfaces. ● It also provides a runtime EntityManager API for processing queries and transactions on the objects against the database. ● It uses a platform-independent object-oriented query language JPQL (Java Persistent Query Language). In the context of persistence, it covers three areas: ● The Java Persistence API ● Object-Relational metadata ● The API itself, defined in the persistence package JPA is not a framework. It defines a concept that can be implemented by any framework.
  • 79.
    Why should weuse JPA? JPA is simpler, cleaner, and less labor-intensive than JDBC, SQL, and handwritten mapping. JPA is suitable for non-performance oriented complex applications. The main advantage of JPA over JDBC is that, in JPA, data is represented by objects and classes while in JDBC data is represented by tables and records. It uses POJO to represent persistent data that simplifies database programming. There are some other advantages of JPA: ● JPA avoids writing DDL in a database-specific dialect of SQL. Instead of this, it allows mapping in XML or using Java annotations. ● JPA allows us to avoid writing DML in the database-specific dialect of SQL. ● JPA allows us to save and load Java objects and graphs without any DML language at all. ● When we need to perform queries JPQL, it allows us to express the queries in terms of Java entities rather than the (native) SQL table and columns.
  • 80.
    JPA Features ● Itis a powerful repository and custom object-mapping abstraction. ● It supports for cross-store persistence. It means an entity can be partially stored in MySQL and Neo4j (Graph Database Management System). ● It dynamically generates queries from queries methods name. ● The domain base classes provide basic properties. ● It supports transparent auditing. ● Possibility to integrate custom repository code. ● It is easy to integrate with Spring Framework with the custom namespace.
  • 81.
    JPA Architecture JPA isa source to store business entities as relational entities. It shows how to define a POJO as an entity and how to manage entities with relation.
  • 82.
    JPA Architecture ● Persistence:It is a class that contains static methods to obtain an EntityManagerFactory instance. ● EntityManagerFactory: It is a factory class of EntityManager. It creates and manages multiple instances of EntityManager. ● EntityManager: It is an interface. It controls the persistence operations on objects. It works for the Query instance. ● Entity: The entities are the persistence objects stores as a record in the database. ● Persistence Unit: It defines a set of all entity classes. In an application, EntityManager instances manage it. The set of entity classes represents the data contained within a single data store. ● EntityTransaction: It has a one-to-one relationship with the EntityManager class. For each EntityManager, operations are maintained by EntityTransaction class. ● Query: It is an interface that is implemented by each JPA vendor to obtain relation objects that meet the criteria.
  • 83.
    JPA Class Relationships ●The relationship between EntityManager and EntiyTransaction is one-to-one. There is an EntityTransaction instance for each EntityManager operation. ● The relationship between EntityManageFactory and EntiyManager is one-to-many. It is a factory class to EntityManager instance. ● The relationship between EntityManager and Query is one-to-many. We can execute any number of queries by using an instance of EntityManager class. ● The relationship between EntityManager and Entity is one-to-many. An EntityManager instance can manage multiple Entities.
  • 84.
  • 85.
    What is webservice? • A web service is a set of open protocols and standards that allow data to be exchanged between different applications or systems. • Web services can be used by software programs written in a variety of programming languages and running on a variety of platforms to exchange data via computer networks such as the Internet in a similar way to inter-process communication on a single computer. • Any software, application, or cloud technology that uses standardized web protocols (HTTP or HTTPS) to connect, interoperate, and exchange data messages – commonly XML (Extensible Markup Language) – across the internet is considered a web service.
  • 86.
    What is aREST API? ● An API, or application programming interface, is a set of rules that define how applications or devices can connect to and communicate with each other. ● A REST API is an API that conforms to the design principles of the REST, or representational state transfer architectural style. For this reason, REST APIs are sometimes referred to RESTful APIs. ● A REST API is designed to provide a lightweight form of communication (less bandwidth) between producer (ex: Twitter) and consumer (ex: Twitter client) ● REST APIs provide a flexible, lightweight way to integrate applications, and have emerged as the most common method for connecting components in microservices architectures.
  • 87.
    How REST APIswork REST APIs communicate via HTTP requests to perform standard database functions like creating, reading, updating, and deleting records (also known as CRUD) within a resource. For example, a REST API would use a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one. All HTTP methods can be used in API calls. A well-designed REST API is similar to a website running in a web browser with built-in HTTP functionality. The state of a resource at any particular instant, or timestamp, is known as the resource representation. This information can be delivered to a client in virtually any format including JavaScript Object Notation (JSON), HTML, XLT, Python, PHP, or plain text. Request headers and parameters are also important in REST API calls because they include important identifier information such as metadata, authorizations, uniform resource identifiers (URIs), caching,cookies and more. Along with conventional HTTP status codes, are used within well-designed REST APIs.
  • 88.
    RESTful API isan application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data
  • 89.
    Write a programto demonstrate RESTful Web Services with spring boot.(Product Application) Download and Install Postman: www.postman.com Refer : https://docs.google.com/document/d/13mwTBiMPDGnL_PHa3UrkuCS6VqfO pJoF6hL-7KPgwb8/edit?usp=sharing
  • 90.
    Introduction to RESTfulWeb Services REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding, who also developed HTTP. The main goal of RESTful web services is to make web services more effective. RESTful web services try to define services using the different concepts that are already present in HTTP. REST is an architectural approach, not a protocol. It does not define the standard message exchange format. We can build REST services with both XML and JSON. JSON is more popular format with REST. The key abstraction is a resource in REST. A resource can be anything. It can be accessed through a Uniform Resource Identifier (URI).
  • 91.
    Introduction to RESTfulWeb Services The resource has representations like XML, HTML, and JSON. The current state capture by representational resource. When we request a resource, we provide the representation of the resource. The important methods of HTTP are: ● GET: It reads a resource. ● PUT: It updates an existing resource. ● POST: It creates a new resource. ● DELETE: It deletes the resource. EXAMPLE : POST /users: It creates a user. GET /users/{id}: It retrieves the detail of a user. GET /users: It retrieves the detail of all users. DELETE /users: It deletes all users. DELETE /users/{id}: It deletes a user. GET /users/{id}/posts/post_id: It retrieve the detail of a specific post. POST / users/{id}/ posts: It creates a post of the user.
  • 92.
    Spring Boot -Building RESTful Web Services Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot. Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file. If you are a Maven user, use the following code to add the below dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> If you are a Gradle user, use the following code to add the below dependency in your build.gradle file. compile('org.springframework.boot:spring-boot-starter-web')
  • 93.
    Spring Boot -Building RESTful Web Services Rest Controller The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below − @RestController public class ProductServiceController { }
  • 94.
    Spring Boot -Building RESTful Web Services Request Mapping The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET. @RequestMapping(value = "/products") public ResponseEntity<Object> getProducts() { } @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET). We can apply @GetMapping only on method level and @RequestMapping annotation can be applied on class level and as well as on method level. @GetMapping is the newer annotaion.
  • 95.
    Spring Boot restfulWeb services Request Body The @RequestBody annotation is used to define the request body content type. //create new service=@RequestBody public ResponseEntity<Object> createProduct(@RequestBody Product product) { }
  • 96.
    Spring Boot restfulWeb services Path Variable The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below − public ResponseEntity<Object> updateProduct(@PathVariable("id") String id) { //update //delete }
  • 97.
    Spring Boot restfulWeb services Request Parameter The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here − public ResponseEntity<Object> getProduct( @RequestParam(value = "name", required = false, defaultValue = "honey") String name) { }
  • 98.
    Get API(Read operation) Thedefault HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL.
  • 99.
    Post API(Create Operation) TheHTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL.
  • 100.
    Put API The HTTPPUT request is used to update the existing resource This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL.
  • 101.
    Delete API The HTTPDelete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL.
  • 102.
    Spring Boot -Building RESTful Web Services The Spring Boot main application class – DemoApplication.java package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }
  • 103.
    The POJO class– Product.java package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
  • 104.
    The Rest Controllerclass – ProductServiceController.java package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>();
  • 105.
    static { Product honey= new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable("id") String id) { productRepo.remove(id); return new ResponseEntity<>("Product is deleted successsfully", HttpStatus.OK); }
  • 106.
    @RequestMapping(value = "/products/{id}",method = RequestMethod.PUT) //update or create public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successsfully", HttpStatus.OK); } @RequestMapping(value = "/products", method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>("Product is created successfully", HttpStatus.CREATED); } @RequestMapping(value = "/products") public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); }
  • 107.
    GET API URLis: http://localhost:8080/products
  • 108.
    POST API URLis: http://localhost:8080/products
  • 109.
    PUT API URLis: http://localhost:8080/products/3
  • 110.
    DELETE API URLis: http://localhost:8080/products/3

Editor's Notes

  • #3 10 min : https://www.youtube.com/watch?v=gq4S-ovWVlM
  • #4  https://docs.spring.io/spring-framework/docs/3.2.0.RC1/reference/html/jdbc.html https://www.javatpoint.com/spring-JdbcTemplate-tutorial http://itmyhome.com/spring/jdbc.html
  • #6 https://spring.io/projects/spring-boot https://www.youtube.com/watch?v=35EQXmHKZYs https://www.ibm.com/cloud/learn/java-spring-boot Diff bet : https://www.interviewbit.com/blog/spring-vs-spring-boot/#:~:text=In%20the%20Spring%20framework%2C%20you,configurations%20that%20allow%20faster%20bootstrapping.&text=Spring%20Framework%20requires%20a%20number,working%20with%20just%20one%20dependency.
  • #19 https://www.tutorialspoint.com/spring_boot/spring_boot_introduction.htm
  • #22 https://stackoverflow.com/questions/21579247/plugin-org-apache-maven-pluginsmaven-compiler-plugin-or-one-of-its-dependencies https://www.youtube.com/watch?v=ZJ7afDSrb3s https://www.javatpoint.com/spring-boot-annotations
  • #29 https://www.youtube.com/watch?v=mS1L96GqwSU
  • #30 https://www.logicbig.com/how-to/code-snippets/jcode-spring-boot-springapplication.html Spring Application
  • #33 https://www.logicbig.com/how-to/code-snippets/jcode-spring-boot-springapplication.html package com.journaldev.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestApplication.class, args); } } https://www.journaldev.com/21556/springbootapplication-springapplication
  • #34 https://www.javatpoint.com/spring-boot-architecture
  • #54 https://www.youtube.com/watch?v=GyFBp5v4tHY https://spring.io/guides/gs/accessing-data-jpa/ https://spring.io/guides/gs/accessing-data-mysql/ https://www.javatpoint.com/spring-boot-jpa shweta
  • #55 https://www.codejava.net/frameworks/spring-boot/connect-to-postgresql-database-examples
  • #76 https://www.codejava.net/frameworks/spring-boot/connect-to-postgresql-database-examples https://www.codejava.net/frameworks/spring/spring-mvc-with-jdbctemplate-example
  • #94 https://www.tutorialspoint.com/spring_boot/spring_boot_building_restful_web_services.htm https://www.tutorialspoint.com/spring_boot/spring_boot_building_restful_web_services.htm
  • #102  https://www.tutorialspoint.com/spring_boot/spring_boot_building_restful_web_services.htm https://www.codejava.net/frameworks/spring-boot/connect-to-postgresql-database-examples https://www.codejava.net/frameworks/spring-boot/connect-to-postgresql-database-examples