You are on page 1of 20

TRAINING

CHAPTER -I
(with 4 New Pages in
last)

Following will be covered for first chapter:-

1.Introduction of spring boot.


2.Required Software installation (STS, postman, dbeaver, mysql, lombok)
3.Demo spring boot project download and make required db connectivity.
4.Implement Task of the day.(Basic CRUD with single table).
5.API testing by Postman.
1.Introducing Spring Boot
Spring Boot helps you to create stand-alone, production-grade
Spring-based applications that you can run. We take an opinionated view
of the Spring platform and third-party libraries, so that you can get started
with minimum fuss. Most Spring Boot applications need very little Spring
configuration.

You can use Spring Boot to create Java applications that can be started by using java
-jar or more traditional war deployments.
Our primary goals are:
● Provide a radically faster and widely accessible getting-started experience for
all Spring development.
● Be opinionated out of the box but get out of the way quickly as requirements
start to diverge from the defaults.
● Provide a range of non-functional features that are common to large classes
of projects (such as embedded servers, security, metrics, health checks, and
externalized configuration).
● Absolutely no code generation (when not targeting native image) and no
requirement for XML configuration.

Document Ref: https://docs.spring.io

System Requirements
Spring Boot 3.0.3 requires Java 17 and is compatible up to and including Java 19.
Spring Framework 6.0.5 or above is also required.
Explicit build support is provided for the following build tools:
Build Tool Version

Maven 3.5+

Gradle 7.x (7.5 or later)

2.Required Software Installation:

Useful Links :
1.STS installation
https://spring.io/tools

2.MySql installation
https://dev.mysql.com/downloads/mysql/

3.DBeaver Installation
https://dbeaver.io/download/

4.Postman Installation
https://www.postman.com/downloads/
https://www.youtube.com/results?search_query=postman+install+

5.Lombok installation and use


Project Lombok is a java library tool that is used to minimize/remove the
boilerplate code and save the precious time of developers during development
by just using some annotations. In addition to it, it also increases the readability of
the source code and saves space.

Ref: https://codippa.com/lombok/installing-lombok
3. Downloading simple demo project
A. Visit : https://start.spring.io/
B. Select minimum required dependency for spring project.
1.Spring Web
2.Lombok
3.Mysql
4.Spring Data Jpa
5.Spring Boot dev tools
#datasource configurations setup (write this configuration in
application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-demo?useJDBCCompliantTimezone
Shift=true&createDatabaseIfNotExist=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.port=8080
What is JSON data?
JSON (JavaScript Object Notation) is the most widely used data format for
data interchange on the web. JSON is a lightweight text-based,
data-interchange format and it is completely language-independent. It is
based on a subset of the JavaScript programming language and it is easy to
understand and generate.

JSON supports mainly 6 data types:

1. String

2. Number

3. Boolean

4. Null

5. Object

6. Array
Example of JSON document:

{
"Geeks" : [
{
"Geekname" : "Sahil kumar",
"subject" : "Data structures",
"Articles" : 10
},
{
"Geekname" : "Pawan singh",
"subject" : "Algorithms",
"Articles" : 16
},
{
"Geekname" : "Ayush Goel",
"subject" : "Networking",
"Articles" : 7
}
]
}

4. Writing the Code for demo project.


To finish our application, we need to create a single Java file. By default, Maven
compiles sources from src/main/java, so you need to create that directory structure
and then add a file named src/main/java/MyApplication.java to contain the following
code:

Here I am providing basic data flow structure and processing classes used for any
modules.

1.Main class Creation

@RestController
@SpringBootApplication
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
@ComponentScan(basePackages = { "com" })
@EntityScan(basePackages = {"com.example.demo.entities"})
public class MyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

2.Controller class Creation

@RestController
@RequestMapping(value = "/api/v1/demo", produces =
MediaType.APPLICATION_JSON_VALUE)
public class DemoController {

@Autowired
Private DemoService demoService;

@RequestMapping( value = "/{id}"


method = {RequestMethod.GET })
Public ResponseEntity get(
@PathVariable(name = "id", required = true , default=”0”) long id
) {
return demoService.get(id);
}

@RequestMapping(method = {RequestMethod.POST })
public ResponseEntity save(@RequestBody DemoRequest request)
{
return demoService.save(request);
}

@RequestMapping(method = {RequestMethod.PUT })
public ResponseEntity update(@RequestBody DemoRequest
request) {
return demoService.update(request);
}
@RequestMapping( method = {RequestMethod.DELETE })
public ResponseEntity delete(
@RequestParam(value="id", required=true,default=”0”) long id
) {
return demoService.delete(id);
}
}

3.Service class Creation (We say handler also to this class)

@Component
public class DemoService {

@Autowired
private DemoRepository demoRepo;

public ResponseEntity save(Demorequest request) {


try{
DemoMapper mapper=new DemoMapper();
Demo demo =mapper.map(request);
demoRepo.save(demo);
return new ResponseEntity(demo, HttpStatus.OK);
}catch(Exception e){
e.printStackTrace();
return new ResponseEntity(demo,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}

public ResponseEntity update(Demorequest request) {


try{
DemoMapper mapper=new DemoMapper();
Demo demo =mapper.map(request);
demoRepo.save(demo);
return new ResponseEntity(demo, HttpStatus.OK);
}catch(Exception e){
e.printStackTrace();
return new ResponseEntity(demo,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}

public ResponseEntity get(long id) {


Demo demo =demoRepo.findById(id).orElse(null);
if(demo!=null){
return new ResponseEntity(demo, HttpStatus.OK);
}else{
return new ResponseEntity(null, HttpStatus.NO_CONTENT
);
}
}

public ResponseEntity delete(long id) {


Demo demo =demoRepo.findById(id).orElse(null);
if(demo!=null){
demoRepo.delete(demo);
return new ResponseEntity(demo, HttpStatus.OK);
}else{
return new ResponseEntity(null, HttpStatus.NO_CONTENT
);
}
}
}

4.Request class Creation

public class DemoRequest {


private String name;
private int age;
}

5.Mapper Class Creation


public class DemoMapper{
public Demo map(DemoRequest request){
Demo demo=new Demo();
if(request.getId()>0){
demo.setId(request.getId());
}
demo.setName(request.getName());
demo.setAge(request.getAge());
return demo;
}
}

6.Entity Class Creation

@Entity
@Table(name=”demo”)
class @Data Demo{
@Id
@Column(name=”demo_id”)
private long id;
@Column(name=”name”)
private String name;
@Column(name=”age”)
private int age;
}
7.Persistence interface creation
We don't need to use @Repository or @Component or @Service annotation when we are
extending JpaRepository because Spring detects that the predefined JpaRepository has
been extended and recognises the interface that extends JpaRepository as a repository.

public interface DemoRepository extends JpaRepository<Demo, Long> {


//here we write any code when we need to use jpa custom methods
}

5.Some Important Annotation Details:

Although there is not much code here, quite a lot is going on. We step through the
important parts in the next few sections.

The @RestController and @RequestMapping Annotations


The first annotation on our MyApplication class is @RestController. This is known as
a stereotype annotation. It provides hints for people reading the code and for Spring
that the class plays a specific role. In this case, our class is a web @Controller, so
Spring considers it when handling incoming web requests.
The @RequestMapping annotation provides “routing” information. It tells Spring that
any HTTP request with the / path should be mapped to the home method. The
@RestController annotation tells Spring to render the resulting string directly back to
the caller.
The @RestController and @RequestMapping annotations are Spring MVC
annotations (they are not specific to Spring Boot). See the MVC section in the Spring
Reference Documentation for more details

The @SpringBootApplication Annotation


The second class-level annotation is @SpringBootApplication. This annotation is
known as a meta-annotation, it combines @SpringBootConfiguration,
@EnableAutoConfiguration and @ComponentScan.
Of those, the annotation we’re most interested in here is @EnableAutoConfiguration.
@EnableAutoConfiguration tells Spring Boot to “guess” how you want to configure
Spring, based on the jar dependencies that you have added. Since
spring-boot-starter-web added Tomcat and Spring MVC, the auto-configuration
assumes that you are developing a web application and sets up Spring accordingly.
Starters and Auto-configuration
Auto-configuration is designed to work well with “Starters”, but the two concepts are
not directly tied. You are free to pick and choose jar dependencies outside of the
starters. Spring Boot still does its best to auto-configure your application.

The “main” Method


The final part of our application is the main method. This is a standard method that
follows the Java convention for an application entry point. Our main method
delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication
bootstraps our application, starting Spring, which, in turn, starts the auto-configured
Tomcat web server. We need to pass MyApplication.class as an argument to the run
method to tell SpringApplication which is the primary Spring component. The args
array is also passed through to expose any command-line arguments.

Running the Example


At this point, your application should work. Since you used the
spring-boot-starter-parent POM, you have a useful run goal that you can use to start
the application. Type mvn spring-boot:run from the root project directory to start the
application. You should see output similar to the following:

$ mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.0.3)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 0.906 seconds (process running for 6.514)

Note: If you open a web browser to localhost:8080, you should see the following
output:
Hello World!
To gracefully exit the application, press ctrl-c.

Dependency Management
Each release of Spring Boot provides a curated list of dependencies that it supports.
In practice, you do not need to provide a version for any of these dependencies in
your build configuration, as Spring Boot manages that for you. When you upgrade
Spring Boot itself, these dependencies are upgraded as well in a consistent way.

Each release of Spring Boot is associated with a base version of the Spring
Framework. We highly recommend that you do not specify its version.

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.

https://www.baeldung.com/spring-dependency-injection
https://www.baeldung.com/spring-autowire

Using application.yml vs application.properties in Spring


Boot
We can use properties files, YAML files, environment variables and command-line
arguments.

In this short tutorial, we'll explore the main differences between properties and YAML
files.

https://www.baeldung.com/spring-boot-yaml-vs-properties

https://www.geeksforgeeks.org/difference-between-yaml-yml-and-properties-file-in-java-s
pringboot/

#datasource dependency (inject this dependency in pom file if not available)

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

What is use of POM.xml file?


A Project Object Model or POM is the fundamental unit of work in Maven. It is an
XML file that contains information about the project and configuration details used by
Maven to build the project. It contains default values for most projects.

The spring-boot-starter-parent is a project starter. It provides default configurations


for our applications. It is used internally by all dependencies. All Spring Boot projects
use spring-boot-starter-parent as a parent in pom.xml file.

https://www.javatpoint.com/maven-pom-xml
https://www.tutorialspoint.com/spring_boot/spring_boot_build_systems.htm
Understanding logging in Spring Boot
https://medium.com/javarevisited/understanding-logging-in-spring-boot-ac0fd79177
b4#:~:text=Spring%20Boot%20comes%20with%20SLF4J,framework%20comes%20
with%20three%20elements

Other References
https://www.geeksforgeeks.org/spring-dependency-injection-with-example/
https://www.javatpoint.com/spring-boot-properties

Chapter1 Meeting Day-2

1.Response Structure Model.


2.CustomResponse Model for any Entity.
3. @JsonProperty, @jsonIgnore use.
4.Project package structure.
5.Task-B for chapter 1.

1.ResponseEntityObject:-

public @Data class ResponseEntityObject<T> {


private Boolean status;
private String message;
private T object;
private Long totalItems;
private HttpStatus httpStatus;
private int httpCode;
public ResponseEntityObject() {
}
public ResponseEntityObject(HttpStatus httpStatus, int httpCode, boolean status, String message, T
obj,Long totalItems) {
super();
this.status = status;
this.message = message;
this.object = obj;
this.httpStatus = httpStatus;
this.httpCode = httpCode;
this.totalItems = totalItems;
}

public ResponseEntityObject(HttpStatus httpStatus, int httpCode, boolean status, String message,T


list) {
super();
this.status = status;
this.message = message;
this.object = list;
this.httpStatus = httpStatus;
this.httpCode = httpCode;
}

public ResponseEntityObject(boolean status, String message, T obj,Long totalItems) {


super();
this.status = status;
this.message = message;
this.object = obj;
this.totalItems = totalItems;
}

public ResponseEntityObject(boolean status, String message, T obj) {


super();
this.status = status;
this.message = message;
this.object = obj;
}

public ResponseEntityObject(boolean status, String message) {


super();
this.status = status;
this.message = message;
}
}

Example:
public ResponseEntity getList(){

try {
List<Demo> demoList =demoRepo.findAll();

List<DemoResponse> responseList =new ArrayList<>();

for(Demo demo: demoList) {


DemoResponse response=new DemoResponse();
response.setName(demo.getName());
responseList.add(response);
}

long count =demoList.size();

return new ResponseEntity(new ResponseEntityObject(true,


"SUCCESSFULLY FETCH" ,responseList, count ) , HttpStatus.OK);

}catch(Exception e) {
e.printStackTrace();

return new ResponseEntity(null,


HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}

2.DemoResponse Model

public @Data DemoResponse{


Private String name;
}
.
3 @JsonProperty, @jsonIgnore – JsonIgnore remove that
particular attribute from object. And @JsonProperty make rename
that particular attribute in json data.

4.Project Package Structure:-


com.example.demo //put main class here
com.example.demo.entities // put entity file
com.example.demo.module //put service,controller, repository
com.example.demo.model //put req, resp
com.example.demo.constants //put constant file

Chaper-1 Task A:-


Create Entity Employee with name, age, salary, joiningDate
and create basic CRUD operations.
Chaper-1 Task B:-
Create 5 employees in table with joining date 1june, 5june,
7june, 10june, 12june for year 2023. Now use JPA default
method findAll to fetch data and process at server if joining date
between 2 june to 8 june and name contains ‘mohan’ then
return those employee list json with name only in response.

Note:-Task Submission time is before 6PM.

—----THANK YOU—--

You might also like