0% found this document useful (0 votes)
19 views37 pages

Final Spring Boot Documentation

Uploaded by

Arti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views37 pages

Final Spring Boot Documentation

Uploaded by

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

Project Name : Student Record Database

Project Tool Requirements:


 Spring Tool Suite (STS)
 Java 17
 Maven 3.6.3
 SQL Server Workbench
Dependencies:
1. Spring Data JPA
2. MySQL Driver
3. Spring Dev-Tools
4. Thymeleaf
5. MyBatis
6. Spring Web
7. Validation
8. Testing

Project Architecture:

Here's how the flow works in a Spring Boot MVC


application:
1. The user interacts with the application through the user interface (UI) provided by the View.
2. The View sends a request to the appropriate Controller based on the user's action.
3. The Controller receives the request, processes it (e.g., retrieves data from the Model,
performs business logic), and prepares the data to be displayed.
4. Once the data is prepared, the Controller selects an appropriate View and passes the data to
it.
5. The View renders the data received from the Controller into HTML or other suitable formats
and sends it back to the user's browser.
6. The user sees the updated UI and can continue interacting with the application, initiating a
new cycle if needed.

Here are some key differences between entities and


DTOs:
 Purpose: Entities represent persistent data objects mapped to database tables, while DTOs
are used for transferring data between different layers or components of an application.
 Content: Entities contain fields representing database columns and may include persistence-
related logic, whereas DTOs contain only data fields relevant to a specific use case or
operation.
 Usage: Entities are primarily used within the data access layer for database operations, while
DTOs are used for communication between different layers, such as between Controllers and
Services or between Services and external systems.
 Mapping: Entities are often directly mapped to database tables using ORM frameworks,
while DTOs are manually created to match the requirements of specific data transfer
scenarios.

DTO (Data Transfer Object):


 Purpose:
 DTOs represent the data transfer objects used for transferring data between different
layers of your application, primarily between your controller and service layers.
 They usually mirror the structure of your domain entities but may not contain
business logic.
 Usage: DTOs are used to transfer data from the client (usually in JSON format in
REST APIs) to the server and vice versa.
 They provide a way to encapsulate data in a structured format.
 Interactions: DTOs are typically used as method parameters or return types in the
controller layer to pass data to and from the client.
2. Entity:
 Purpose: Entities represent persistent data stored in a database.
 They often map directly to database tables and may contain additional logic or
annotations for persistence mapping.
 Usage: Entities are used to represent data in the database.
 They encapsulate the state of an object and typically have methods for CRUD
operations.
 Interactions: Entities are commonly used by the repository layer to interact with the
database.
 They are also returned by the repository layer to the service layer, which then may
convert them to DTOs before passing them to the controller layer.
3. Controller:
 Purpose: Controllers handle incoming HTTP requests, delegate the processing to the
service layer, and return appropriate responses.
 Usage: Controllers define the API endpoints and handle incoming HTTP requests.
 They receive input data from the client, validate it, and pass it to the service layer for
processing.
 Interactions: Controllers interact with DTOs as method parameters and return types.
 They use DTOs to receive data from the client and may return DTOs as responses.
4. Repository:
 Purpose: Repositories are responsible for data access and manipulation.
 They provide an abstraction over the database operations.
 Usage: Repositories define methods for CRUD operations and other data access
logic.
 They interact directly with the database using SQL queries or ORM frameworks like
MyBatis or Hibernate.
 Interactions: Repositories interact with entities to perform database operations.
 They typically return entities to the service layer for further processing.
5. Service:
 Purpose: Services contain the business logic of your application.
 They orchestrate interactions between different components and enforce business
rules.
 Usage: Services implement business logic, coordinate transactions, and enforce
security and validation rules.
 They may involve multiple repository calls or external services.
 Interactions: Services interact with repositories to perform data access and
manipulation.
 They may receive entities from repositories, apply business logic, and return DTOs
to the controller layer.
6. Service Implementation (ServiceImpl):
 Purpose: Service implementations provide concrete implementations of the service
interfaces.
 Usage: Service implementations contain the actual implementation of business logic
defined in the service interfaces.
 They interact with repositories to fetch or persist data and may perform additional
processing.
 Interactions: Service implementations interact with repositories to perform database
operations.
 They receive entities from repositories, apply business logic, and return DTOs to the
controller layer.
7. MyBatis Mapper:
 Purpose: MyBatis mappers provide a way to map SQL queries to Java methods.
 They handle database interactions and return mapped results.
 Usage: MyBatis mappers contain SQL queries and mapping instructions.
 They are used by the repository layer to execute database operations.
 Interactions: MyBatis mappers are invoked by repository implementations to
execute SQL queries and map the results to entities.
 They provide a bridge between Java code and the underlying database.

1. Spring Data JPA:


 Spring Data JPA is a part of the larger Spring Data project that aims to simplify data
access in Spring-based applications.
 It provides an abstraction layer on top of JPA (Java Persistence API) to ease the
development of data access layers by reducing boilerplate code.
 Spring Data JPA simplifies the creation of repository classes for database operations
by providing built-in support for common CRUD (Create, Read, Update, Delete)
operations and query methods.
2. MySQL Driver:
 The MySQL Driver is a Java library used to connect Java applications to MySQL
databases.
 It provides the necessary functionality to establish a connection to a MySQL
database, send queries, and retrieve results.
 The MySQL Driver is essential for Java applications that need to interact with
MySQL databases, including those developed using Spring frameworks.
3. Spring Dev-Tools:
 Spring Dev-Tools is a set of tools provided by the Spring Boot framework to enhance
the development experience and productivity.
 It includes features such as automatic application restarts, live reload of static
resources, and remote debugging support.
 Spring Dev-Tools aims to streamline the development process by reducing the time
spent on repetitive tasks and improving the developer's workflow.
4. Thymeleaf:
 Thymeleaf is a modern server-side Java template engine for web and standalone
environments.
 It allows developers to build web applications using natural templates written in
HTML with added attributes for processing by Thymeleaf.
 Thymeleaf supports features such as expression language (EL) for dynamic content
rendering, template inheritance, internationalization, and more.
 It is commonly used in Spring Boot applications for server-side rendering of web
pages.
5. MyBatis:
 MyBatis is a lightweight persistence framework for Java applications that simplifies
database access and mapping of SQL statements to Java methods.
 It provides a simple XML-based configuration for defining SQL mappings and a set
of annotations for mapping Java objects to database tables.
 MyBatis offers features like dynamic SQL generation, caching, and transaction
management, making it a popular choice for database access in Java applications.
6. Spring Web:
 Spring Web is a part of the Spring Framework that provides features and utilities for
building web applications in Java.
 It includes components for handling HTTP requests and responses, managing web
sessions, handling file uploads, and more.
 Spring Web supports various web technologies and protocols, making it versatile for
building both traditional server-side rendered applications and modern RESTful
APIs.
7. Validation:
 Validation refers to the process of ensuring that data entered by users meets specified
criteria or constraints.
 In the context of Spring applications, validation can be performed using annotations
like @NotNull, @Size, @Email, etc., or by implementing custom validators.
 Validation helps in maintaining data integrity, improving user experience by
providing feedback on input errors, and preventing invalid data from being processed
by the application.
8. Testing:
 Testing is the process of verifying that software behaves as expected under various
conditions.
 In the context of Spring applications, testing involves writing and executing
automated tests to validate the behavior of components such as controllers, services,
repositories, etc.
 Spring applications can be tested using frameworks like JUnit, Mockito, Spring Test,
etc., to ensure correctness, reliability, and maintainability of the codebase.

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.

 Spring MVC Architecture:


Spring MVC (Model-View-Controller) is a design pattern used to develop web applications
in Java.
 It divides an application into three main components:
 Model:
 Represents the application's data and business logic.
 View: Renders the user interface for presenting data to the user.
 Controller: Handles user requests, processes them, and invokes appropriate actions, such as
calling services to perform business logic and preparing data to be displayed.

 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.

 DTO (Data Transfer Object):


 DTOs are used for transferring data between different layers of the application, such as
between the Controller and the Service layer.
 DTOs are lightweight objects that contain only the necessary data for a specific operation or
use case.
 They help in decoupling the layers of the application and reducing the amount of data
transferred over the network.
 DTOs are typically simple Java classes with fields, getters, and setters, but no business logic.

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.

 4. Run your tests:


 Use your IDE's built-in test runner or execute your test class using a build tool like Maven or
Gradle.
 Analyze the test results to ensure that all tests pass and that your code behaves as expected.
 @Test annotation in JUnit is used to mark a method as a test method. When JUnit
runs tests, it identifies methods annotated with @Test and executes them to verify
that the code under test behaves as expected. Here's a detailed overview of the
@Test annotation:

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.

It contains methods annotated with @ExceptionHandler to handle specific types of


exceptions.
The GlobalExceptionHandler class, located in the net.shadervertex.sms.exception
package, serves as a central point for handling exceptions thrown by REST controllers.
It imports necessary classes from the Spring Framework, including HttpStatus,
ResponseEntity, and exception classes like MethodArgumentNotValidException and
BindException.
This class is annotated with @RestControllerAdvice, indicating that it provides global
exception handling advice for REST controllers in the application.
Two exception handling methods are defined within the class.
The first method, annotated with
@ExceptionHandler(MethodArgumentNotValidException.class), handles validation errors
that occur when validating request parameters or request bodies.
Inside this method, a HashMap is initialized to store field errors and their corresponding
error messages.
It iterates over all validation errors using a lambda expression, extracting the field name
and error message from each error and storing them in the map. Finally, a ResponseEntity
is constructed with a status of BAD_REQUEST and the map of errors as the response
body.
Similarly, the second method, annotated with @ExceptionHandler(BindException.class),
handles binding errors that occur during data binding. It follows the same approach as the
first method to collect field errors and their error messages into a map and construct a
ResponseEntity with a status of BAD_REQUEST.


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

Step 2: Compile the project using Maven.

mvn compile

Step 3: Package the project into a JAR file.

mvn package

Step 4: Run test cases.

mvn test

Step 5: Execute the JAR file generated in the target directory.

java -jar /path/to/your/project/target/your-project-name.jar

Step 6: Once the application is running, open a web browser and navigate to the specified endpoint.

localhost:6047/login

ScreenShot actual running project


1)
2)

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

# Set the working directory to /student-management-system-springboot-main


WORKDIR /student-management-system-springboot-main

# Copy the current directory contents into the container at /student-management-system-


springboot-main
COPY . .

# Build the Java application


RUN mvn clean install

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.

# Use an official MySQL image as the database


FROM mysql:latest

# Set the MySQL root password


ENV MYSQL_ROOT_PASSWORD=@@@Root87

# Set up the database and user


ENV MYSQL_DATABASE=sms
ENV MYSQL_USER=root
ENV MYSQL_PASSWORD=@@@Root87

# Copy the database schema script into the container


COPY ./database/schema.sql /docker-entrypoint-initdb.d/

# Expose the port for MySQL


EXPOSE 3306

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.

# Use an official OpenJDK image as the base image


FROM openjdk:17-slim

# Set the working directory to /student-management-system-springboot-main


WORKDIR /student-management-system-springboot-main
# Copy the built JAR file from the Maven build stage
COPY --from=build
/student-management-system-springboot-main/target/studentrecorddatabase-0.0.1-
SNAPSHOT.jar .

# Expose port 8085 for the Spring Boot application


EXPOSE 8085

# Run the Spring Boot application when the container launches


CMD ["java", "-jar", "studentrecorddatabase-0.0.1-SNAPSHOT.jar"]

How to login dockerhub and how to build and run docker

Step1:
How to push docker image to docker hub
docker login
username:
password:

2) docker build -t student-management-system-springboot-main .


docker build -f Dockerfile -t aratimahe/student-management-system-springboot-main:latest .
3) docker images

4) docker run -p 8085:6047 student-management-system-springboot-main


docker run -d --network host aratimahe/student-management-system-springboot-main:latest

5) run application localhost:6047/login

check output on port:

database stored data


push Docker image to Docker registry Docker hub

docker push aratimahe/student-management-system-springboot-main:latest

steaps to deploy application in kubernetes cluster


6) helm create helmchartstudentrecord

7) minikube start –driver=docker

8)eval $(minikube docker-env)

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

9) docker build -t student-management-system-springboot-main .


docker build -f Dockerfile -t aratimahe/student-management-system-springboot-main:latest .
10) minikube image ls

docker run:
docker run -p 8085:6047 student-management-system-springboot-main

docker run -d --network host aratimahe/student-management-system-springboot-main:latest

11) helm install studentrelease studentrecordchart

12) kubectl get pod


13) kubectl get svc

14) kubectl get deployment

15) minikube ip

16) minikube dashboard

17) minikube service svcname –url

17) minikube ip: Nodeport see the output

How to integrate with jenkins


1) create repo

2) commit project on repo

3) connect github repo with jenkins also create Dockerfile and Jenkinsfile either Jenkins
script

4) login to jenkins

5) create pipeline project name with studentrecordintegratewithjenkins


6) configure repo with jenkins

7) write down the script

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'
}
}
}

stage('Build Maven project') {


steps {
script {
echo 'Building Maven project...'
// Use the 'mvn' command without specifying the full path since Maven is
configured in the 'tools' section
sh 'mvn install'
}
}
}

stage('Build Docker image') {


steps {
script {
// Ensure Docker is installed and available in PATH
sh 'docker --version'

// Build the Docker image


sh "docker build -t ${DOCKER_IMAGE} ${DOCKERFILE_PATH}"

// Print Docker image information


sh "docker images ${DOCKER_IMAGE}"
}
}
}
stage("Push Docker image to Docker Hub") {
steps {
script {
withCredentials([string(credentialsId: 'dockerhubpwd', variable:
'dockerhubpwd')]) {
sh "docker login -u aratimahe -p ${dockerhubpwd}"
}
}
sh "docker push ${DOCKER_IMAGE}"
}
}
stage("Deploy to Kubernetes cluster") {
steps {
script {

kubernetesDeploy (configs: 'deploymentservice.yaml', kubeconfigId: 'k8sid')


}
}
}
}
}

step by step guide how to integrate UI project with jenkins

structure
step 1:
create repo

2) Login to Docker hub registry


3) try to commit all code via terminal
2)

3)
4) create jenkins new project5) manage plugins and set tools like maven jenkins
6) add repo and write jenkins pipeline script

7) jenkins grovvy script or Jenkinsfile

8) run the pipeline and see the ouput


9) docker image push to the dockerhub

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

docker logs lucid_hoover


http://localhost:8089
mysql -u <username> -p -h localhost
docker run -d --network host -p 8089:6047 -p 3306:3306 aratimahe/student-management-
system-springboot-main:latest
docker inspect <container_id> | grep IPAddress

successful but port error

docker run -d --network host aratimahe/student-management-system-springboot-main:latest

http://localhost:8089

docker logs ab0faeb7b32b16dca2c7fb3985b0486ae447a064a7cb40d5dffb2f72bd5f82b0


sudo lsof -i :6047
sudo kill -9 44520
change server.port=6051
docker compose port=8091
docker run -d --network host studentrecorddatabase
docker run -d --network host studentdatabase
docker run -d --network host aratimahe/finalstudproject

<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.

You might also like