Final Spring Boot Documentation
Final Spring Boot Documentation
Project Architecture:
Understanding Concepts:
1. Spring Boot:
Spring Boot is an open-source Java-based framework used to create stand-alone, production-
grade Spring-based applications easily.
2. It simplifies the configuration and setup of Spring-based applications by providing defaults
for various configuration options and taking away much of the boilerplate code required for
setting up Spring projects.
2) MyBatis and JPA (Java Persistence API) are both Java-based persistence frameworks used for
interacting with databases, but they differ in their approach, features, and usage.
1. Approach:
MyBatis: MyBatis is a SQL mapping framework that allows developers to define SQL
queries in XML or annotations and map the results to Java objects.
It provides more control over SQL queries and allows developers to optimize them for
specific database platforms.
With MyBatis, developers have to write SQL queries explicitly.
JPA (Java Persistence API): JPA is a higher-level abstraction that allows developers to
work with objects directly, without having to write SQL queries explicitly.
It provides an object-relational mapping (ORM) approach, where Java objects are mapped to
database tables.
JPA implementations, such as Hibernate, handle the translation of Java objects to SQL
queries and vice versa.
2. Mapping:
MyBatis: In MyBatis, developers have to explicitly define the mapping between SQL
queries and Java objects using XML configuration files or annotations.
JPA (Java Persistence API): JPA provides annotations for defining the mapping between
Java objects and database tables.
It uses metadata annotations to map entities and relationships, reducing the need for explicit
SQL queries.
3. Querying:
MyBatis: Developers have full control over SQL queries in MyBatis. They can write
complex queries tailored to specific database requirements.
JPA (Java Persistence API): JPA offers a higher-level querying interface through JPQL
(Java Persistence Query Language), which is similar to SQL but operates on entities rather
than tables. JPA implementations, such as Hibernate, also support Criteria API for building
type-safe queries dynamically.
4. Performance:
MyBatis: MyBatis provides more control over SQL queries, allowing developers to
optimize them for performance. However, developers need to be careful about writing
efficient SQL queries.
JPA (Java Persistence API): JPA abstracts away SQL queries, which can lead to less
efficient queries being generated. However, JPA implementations often provide caching
mechanisms and other optimizations to improve performance.
5. Learning Curve:
MyBatis: MyBatis is generally considered easier to learn for developers with SQL
experience since it allows direct interaction with SQL queries.
JPA (Java Persistence API): JPA has a steeper learning curve due to its ORM approach and
the need to understand entity mappings and JPQL.
6. Ecosystem:
MyBatis: MyBatis is more lightweight and flexible, making it suitable for projects where
fine-grained control over SQL queries is required.
JPA (Java Persistence API): JPA is part of the Java EE (Enterprise Edition) and Jakarta EE
ecosystem and is widely adopted in Java enterprise applications.
It offers a more standardized approach to persistence in Java applications.
Model:
The Model represents the application's data and business logic.
It encapsulates the state of the application and provides methods for accessing and
manipulating that data.
In the context of Spring MVC and data persistence, the Model often consists of entities
(POJOs representing persistent data), DTOs (Data Transfer Objects used for data exchange
between layers), and service classes (containing business logic).
View:
The View represents the user interface of the application. It is responsible for rendering data
to the user and capturing user input.
Views are typically implemented using technologies like HTML, CSS, JavaScript, and
templating engines (e.g., Thymeleaf in Spring MVC).
Controller:
In the context of Spring MVC (Model-View-Controller), a controller is a Java class responsible for
handling incoming HTTP requests, processing them, and returning an appropriate HTTP response.
Controller:
The Controller acts as an intermediary between the Model and the View.
It receives user requests, processes them, and invokes appropriate actions.
Controllers handle incoming HTTP requests, delegate processing to service classes, prepare
data to be displayed in the View, and return an appropriate response.
In Spring MVC, controllers are typically implemented as Java classes annotated with
@Controller or @RestController.
HTTP Request Methods:
GET: Used to request data from a specified resource.
POST: Used to submit data to be processed to a specified resource.
PUT: Used to update a resource or create a new resource if it does not exist.
DELETE: Used to delete a specified resource.
PATCH: Used to apply partial modifications to a resource.
Annotations in Spring MVC:
@GetMapping: Maps HTTP GET requests onto specific handler methods.
@PutMapping: Maps HTTP PUT requests onto specific handler methods.
@PostMapping: Maps HTTP POST requests onto specific handler methods.
@RequestMapping: Maps HTTP requests to handler methods of MVC and REST
controllers.
Service:
In the context of Spring MVC, a service is a Java class that contains business logic related to
a specific domain or functionality of the application.
It acts as an intermediary between the controller and the repository layer, encapsulating the
business logic and providing reusable methods for processing data.
The Service layer contains the business logic of the application. It encapsulates the
application's core functionality and orchestrates interactions between different components.
Service classes implement use cases and operations defined by the application's
requirements.
Services often interact with repositories to perform CRUD operations on entities, apply
business rules, and manage transactions.
In Spring MVC, service classes are typically implemented as Java classes annotated with
@Service.
Impl:
"Impl" typically stands for implementation.
In the context of Spring, it is a naming convention used for implementing interfaces.
For example, if you have a service interface named UserService, its implementation class
may be named UserServiceImpl, which contains the actual implementation of the methods
defined in the interface.
Repository:
In Spring Data JPA, a repository is an interface that provides CRUD (Create, Read, Update,
Delete) operations for working with entities.
It extends the JpaRepository interface, which provides methods for common database
operations such as saving, updating, deleting, and querying entities.
The Repository provides an abstraction for accessing and manipulating data stored in a
database.
It encapsulates database operations such as saving, updating, deleting, and querying entities.
Repositories typically represent data access objects (DAOs) and interact directly with the
underlying data source (e.g., a relational database).
In Spring Data JPA, repositories are interfaces that extend JpaRepository or other
Spring Data repository interfaces.
Validation:
Validation is the process of ensuring that data entered by a user meets certain criteria set by the
application.
In the context of Spring MVC, validation can be achieved using annotations such as @NotNull,
@Size, @Email, etc., or by implementing custom validators.
It helps in maintaining data integrity and ensuring that only valid data is processed by the
application.
JavaX Validation (now Jakarta Validation):
JavaX Validation was the original Java EE (Enterprise Edition) API for validation,
introduced in Java EE 6.
It provided a set of annotations and APIs for validating Java objects and their
properties.
JavaX Validation was part of the Java EE platform, which is now Jakarta EE after the
transition of Java EE to the Eclipse Foundation.
2. Jakarta Validation API:
Jakarta Validation API is essentially a continuation of JavaX Validation, but with the
package name changed from javax.validation to jakarta.validation.
This renaming is due to the migration of Java EE to the Eclipse Foundation, which
led to the rebranding of various packages from javax.* to jakarta.*.
Jakarta Validation API provides the same set of annotations and APIs as JavaX
Validation but under the jakarta.validation package.
3. Hibernate Validation:
Hibernate Validation is an implementation of the validation API provided by Jakarta
Validation or JavaX Validation.
It builds on top of the validation API and provides additional features and
functionality.
Hibernate Validation integrates seamlessly with Hibernate ORM (Object-Relational
Mapping) framework, allowing validation constraints to be applied directly to entity
classes and persisted to the database.
While Hibernate Validation originally used the javax.validation package, it
has since been updated to support both javax.validation and
jakarta.validation, depending on the version.
Testing:
JUnit is a popular framework for writing and executing unit tests in Java, while
Mockito is a mocking framework that works hand-in-hand with JUnit for creating
mock objects in unit tests.
Here's a brief overview of each:
1. JUnit:
JUnit is a widely-used open-source testing framework for Java.
It provides annotations, assertions, and utilities for writing and running unit tests.
JUnit helps in automating the process of writing and running tests, making it easier to
verify that individual units of code (e.g., methods, classes) behave as expected.
Unit tests written with JUnit typically focus on testing small units of code in isolation
from the rest of the system.
2. Mockito:
Mockito is a mocking framework for Java that allows developers to create mock
objects in unit tests.
Mock objects simulate the behavior of real objects in controlled environments,
allowing developers to isolate the unit of code being tested from its dependencies.
With Mockito, you can create mock objects, define their behavior using stubbing,
verify interactions with them, and more.
Mockito integrates seamlessly with JUnit, making it easy to use both frameworks
together in unit testing.
JUnit Testing: JUnit is a popular open-source unit testing framework for Java. It
provides annotations, assertions, and other utilities for writing and running
automated tests to ensure the correctness of Java code. JUnit tests are typically
written to verify the behavior of individual units (e.g., methods, classes) in isolation
from the rest of the system.
Annotations for Dependency Injection: In Spring Framework, dependency injection is
typically achieved using annotations such as:
@Autowired: Used to automatically wire dependencies by type.
@Qualifier: Used in conjunction with @Autowired to specify which bean should be
injected when multiple beans of the same type are available.
@Resource: Used to inject a named resource, typically by name.
@Inject: Similar to @Autowired, used for dependency injection.
Writing JUnit Test Cases: To write JUnit test cases, follow these general steps:
1. Set up your test environment:
Create a new Java class for your test suite.
Add the necessary imports, including JUnit annotations and any classes you'll be
testing.
2. Write test methods:
Create methods within your test class to test specific behaviors or functionalities of
your code.
Use JUnit annotations such as @Test, @Before, @After, @BeforeEach, and
@AfterEach to annotate your test methods and setup/teardown methods.
3. Write assertions:
Use JUnit's assertion methods (e.g., assertEquals, assertTrue,
assertFalse, etc.) to verify expected outcomes and actual results.
1. Import Statement:
To use the @Test annotation, you need to import it from the JUnit library:
java
import org.junit.jupiter.api.Test;
Usage:
The @Test annotation is applied to a method to indicate that it's a test method.
Test methods should be public and return void.
Test methods can't accept any parameters.
Test Execution:
When JUnit runs, it identifies methods annotated with @Test and executes them as part of
the test suite.
JUnit executes test methods in no particular order, so test methods should be independent
and not rely on the execution order.
Assertions:
Inside a test method annotated with @Test, you typically use assertion methods to verify
that the code under test behaves as expected.
Assertions are provided by JUnit's assertion library, such as assertEquals,
assertTrue, assertFalse, etc.
If an assertion fails during test execution, the test method will fail, and JUnit will report the
failure.
Exception Handling
The GlobalExceptionHandler class in the provided code is responsible for handling
exceptions that may occur during request processing in a Spring MVC application.
How to run project on CLI
To run a Spring Boot project from the command line interface (CLI), follow these
steps:
Step 1: Navigate to the project folder using the terminal.
cd /path/to/your/project
mvn compile
mvn package
mvn test
Step 6: Once the application is running, open a web browser and navigate to the specified endpoint.
localhost:6047/login
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
15)
Dockerfile
1)This part of the Dockerfile is responsible for building the backend Spring Boot
application.
It uses Maven to build the Java application and copies the source code into the container.
# Use an official Maven/Java image as a parent image
FROM maven:3.6.3-openjdk-17-slim AS build
2)
This part of the Dockerfile is responsible for setting up the MySQL database.
It uses the official MySQL Docker image, sets up database configurations (like root
password, database name, user, and password), and copies the database schema script
into the container. So, this file is related to the database.
3)This part of the Dockerfile is responsible for setting up the Spring Boot application.
It uses the built JAR file from the previous Maven build stage, exposes port 8085 for the
Spring Boot application, and specifies the command to run the application. So, this section
is related to the backend.
Step1:
How to push docker image to docker hub
docker login
username:
password:
dynamically configure your local shell environment to use the docker deamon
inside the minikube build pull push docker images from your local machine to the minikube
cluster
docker run:
docker run -p 8085:6047 student-management-system-springboot-main
15) minikube ip
3) connect github repo with jenkins also create Dockerfile and Jenkinsfile either Jenkins
script
4) login to jenkins
script /Jenkinsfile
sample script
pipeline {
agent any
environment {
// Define the Dockerfile location
DOCKERFILE_PATH = '.'
DOCKER_IMAGE = 'aratimahe/student-management-system-springboot-main:latest'
}
tools {
// Define Docker installation name outside of any stage
dockerTool 'dockerimage'
// Define Maven installation name and version outside of any stage
maven 'maven'
}
stages {
stage('Clone code') {
steps {
script {
echo 'Cloning code...'
// Clone the Git repository
git branch: 'master', url: 'https://github.com/deploymentarati/uiproject.git'
}
}
}
structure
step 1:
create repo
3)
4) create jenkins new project5) manage plugins and set tools like maven jenkins
6) add repo and write jenkins pipeline script
Trobleshooting Commands
unsuccessful
docker run -d -p 8089:6047 -p 3306:3306 aratimahe/student-management-system-
springboot-main:latest
unsuccessful
docker run -d -p 8089:6047 -p 3307:3306 aratimahe/student-management-system-
springboot-main:latest
unsuccessful
docker run -d --restart always -p 8089:6047 -p 3307:3306 aratimahe/student-management-
system-springboot-main:latest
unsuccessful
http://localhost:8089
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Many developers use H2 as an embedded database during development and testing because
it's easy to set up, doesn't require a separate database server, and can be configured to start
and stop with your application.