KEMBAR78
Jago Jrahak Program Flow | PDF | Databases | Java (Programming Language)
0% found this document useful (0 votes)
5 views24 pages

Jago Jrahak Program Flow

Uploaded by

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

Jago Jrahak Program Flow

Uploaded by

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

That’s a lot of To-Do items!

I'll break them down one by one, explaining each step, why it's needed, and
its effect on the application.

To-Do Item 1.1: Define JPQL Query


Task:

Define a JPQL query to fetch all complaint details where the `dateOfIncidence` is between two given
dates.

Steps to Implement:

1. Use JPQL (Java Persistence Query Language) to write a query: JPQL is used for queries on
entities instead of raw database tables.
2. Define a named query inside the `ComplaintEntity` class: Named queries are predefined and can
be reused across different parts of the application.
3. Use the `BETWEEN` clause in the query to filter complaints within the date range.

Code Implementation:

java

`@NamedQuery(
name = "getComplaintDetailsByDate",
query = "SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWEEN :fromDate AND :toDate"
)
`

Why?

JPQL is database-independent (works across different databases).


Using a named query improves performance since it is precompiled.
BETWEEN makes it easy to retrieve records within a range.

Effect:

This will allow the application to retrieve all complaints where `dateOfIncidence` falls between `fromDate`
and `toDate`.

To-Do Item 1.2: Define a Custom Repository for `ComplaintTypes`


Task:

Create a custom repository to manage `ComplaintTypeEntity` and fetch all complaint types.

Steps to Implement:

1. Use `@RepositoryDefinition` to define a custom repository: This is an alternative to


`JpaRepository` for custom methods.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/24
2. Define a method to return all complaint types.
3. Use `@Transactional` to manage transactions.

Code Implementation:

java

`@RepositoryDefinition(domainClass = ComplaintTypeEntity.class, idClass = Integer.class)


@Transactional(value = "txManager")
public interface ComplaintTypeDao {
List<ComplaintTypeEntity> findAll();
}
`

Why?

Custom repositories allow fine-grained control over query methods.


`@Transactional` ensures data consistency and rollback on failure.

Effect:

This repository allows retrieving all `ComplaintTypeEntity` records from the database.

To-Do Item 1.3: Register Complaint Details


Task:

Implement a method to register complaints using Spring JPA.

Steps to Implement:

1. Convert `ComplaintBean` to `ComplaintEntity` using `BeanUtils.copyProperties()`.


2. Use `complaintDao.save(complaintEntity)` to persist data.
3. Return the generated complaint ID.

Code Implementation:

java

`public int registerComplaintDetails(ComplaintBean complaintBean) {


ComplaintEntity complaintEntity = covertBeanToEntity(complaintBean);
ComplaintEntity savedEntity = complaintDao.save(complaintEntity);
return savedEntity.getComplaintId();
}

private ComplaintEntity covertBeanToEntity(ComplaintBean complaintBean) {


ComplaintEntity complaintEntity = new ComplaintEntity();
BeanUtils.copyProperties(complaintBean, complaintEntity);
return complaintEntity;
}
`

Why?

Encapsulation: `convertBeanToEntity()` keeps logic separate.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/24
automatically inserts or updates the entity in the database.
`save()`
Improves code maintainability.

Effect:

The method registers complaint details and returns the complaint ID.

To-Do Item 1.4: Retrieve Complaint Details by Date Range


Task:

Retrieve complaints between two dates using `EntityManager`.

Steps to Implement:

1. Use `EntityManager.createQuery()` to execute JPQL.


2. Set query parameters dynamically.
3. Transform results from `ComplaintEntity` to `ComplaintBean`.

Code Implementation:

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


Query query = manager.createQuery("SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWE
query.setParameter(1, fromDate);
query.setParameter(2, toDate);
List<ComplaintEntity> entityList = query.getResultList();
List<ComplaintBean> beanList = new ArrayList<>();

for (ComplaintEntity complaintEntity : entityList) {


beanList.add(convertEntityToBean(complaintEntity));
}
return beanList;
}

private ComplaintBean convertEntityToBean(ComplaintEntity complaintEntity) {


ComplaintBean bean = new ComplaintBean();
BeanUtils.copyProperties(complaintEntity, bean);
return bean;
}
`

Why?

`EntityManager`provides more control over JPQL queries.


Allows batch processing and data transformation.

Effect:

This method retrieves complaints within the specified date range.

To-Do Item 1.5: Retrieve All Complaint Types


Task:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/24
Fetch all complaint types using Spring JPA.

Steps to Implement:

1. Retrieve all entities using `complaintTypeDao.findAll()`.


2. Convert `ComplaintTypeEntity` to `ComplaintTypeBean`.
3. Return a list of `ComplaintTypeBean`.

Code Implementation:

java

`public List<ComplaintTypeBean> getAllComplaintTypes() {


List<ComplaintTypeEntity> entityList = complaintTypeDao.findAll();
List<ComplaintTypeBean> beanList = new ArrayList<>();

for (ComplaintTypeEntity complaintTypeEntity : entityList) {


beanList.add(convertComplaintTypeEntityToBean(complaintTypeEntity));
}
return beanList;
}

private ComplaintTypeBean convertComplaintTypeEntityToBean(ComplaintTypeEntity complaintTypeEntity)


ComplaintTypeBean complaintTypeBean = new ComplaintTypeBean();
BeanUtils.copyProperties(complaintTypeEntity, complaintTypeBean);
return complaintTypeBean;
}
`

Why?

Encapsulates entity-to-bean conversion.


Ensures database abstraction and separation of concerns.

Effect:

Returns all complaint types as a list of `ComplaintTypeBean`.

To-Do Item 1.6: Prevent Duplicate Complaints


Task:

Ensure customers cannot submit duplicate complaints.

Steps to Implement:

1. Call `getCustomerByComplaintType()` to check if a complaint exists.


2. Throw an exception if count is `1`.
3. Otherwise, proceed with complaint registration.

Code Implementation:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/24
java

`public int registerComplaintDetails(ComplaintBean complaintBean) throws Exception {


int count = complaintDaoWrapper.getCustomerByComplaintType(complaintBean.getCustomerName(), comp

if (count == 1) {
throw new Exception("Customer has already submitted a complaint with the same type");
}
return complaintDaoWrapper.registerComplaintDetails(complaintBean);
}
`

Why?

Prevents duplicate records.


Ensures data integrity.

Effect:

A customer cannot submit the same complaint multiple times.

To-Do Item 1.12: Validate Complaint Fields


Task:

Ensure mandatory fields are provided and properly formatted.

Steps to Implement:

1. Use `@NotBlank`, `@NotNull`, `@Past`, and `@DateTimeFormat` annotations.


2. Ensure `dateOfIncidence` is in `dd-MMM-yyyy` format.
3. Ensure `dateOfIncidence` is a past date.

Code Implementation:

java

`@NotBlank(message = "Please Enter Customer Name")


private String customerName;

@NotNull(message = "Please Enter Date of Incidence")


@Past(message = "Date of Incidence must be past date")
@DateTimeFormat(pattern = "dd-MMM-yyyy")
private Date dateOfIncidence;

@NotNull(message = "Please mention total amount of loss")


private Double amount;

@NotNull(message = "Please Enter Complaint Type")


private Integer complaintTypeId;
`

Why?

Ensures proper input validation before processing requests.


Reduces errors and enhances security.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/24
Effect:

Validation ensures data consistency and avoids incorrect submissions.

This covers the major todos. Do you want further explanation on any part? 🚀
This is quite an extensive Spring Boot project with multiple To-Do items related to JPQL, Spring JPA,
Repositories, MVC, and Exception Handling. Below is a detailed step-by-step explanation for each
To-Do item along with the reasoning and its effect.

To-Do Item 1.1: Define JPQL Query

Task

Define a JPQL (Java Persistence Query Language) query to fetch all complaint details where the
dateOfIncidence is between two given dates.

Solution

Modify the named query to fetch complaints within a specific date range.

xml

`<named-query name="getComplaintDetailsByDate">
<query>
SELECT c FROM ComplaintEntity c
WHERE c.dateOfIncidence BETWEEN :startDate AND :endDate
</query>
</named-query>
`

Why?

JPQL uses entity names, not table names (so `ComplaintEntity` instead of `complaint`).
`BETWEEN :startDate AND :endDate` ensures we filter complaints based on date range.
We use named parameters (`:startDate`, `:endDate`) instead of `?1` and `?2` for better
readability.

Effect

This query allows us to efficiently fetch all complaints within a given time frame, helping in
report generation.

To-Do Item 1.2: Define a Custom Repository for ComplaintTypes

Task

Create a custom repository to manage `ComplaintTypeEntity` and add a method to fetch all complaint
types.

Solution

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/24
Modify the repository interface:

java

`@RepositoryDefinition(idClass = Integer.class, domainClass = ComplaintTypeEntity.class)


@Transactional(value = "txManager")
public interface ComplaintTypeDao {
List<ComplaintTypeEntity> findAll();
}
`

Why?

`@RepositoryDefinition` replaces `@Repository`, explicitly defining the ID class and domain


entity.
The method `findAll()` is a Spring Data JPA convention, so it will be automatically
implemented.

Effect

This repository enables easy fetching of all complaint types, making complaint classification
simpler.

To-Do Item 1.3: Register Complaint Details

Task

Implement a method to register a complaint using Spring JPA Data.

Solution

Modify the method as follows:

java

`public int registerComplaintDetails(ComplaintBean complaintBean) {


ComplaintEntity complaintEntity = convertBeanToEntity(complaintBean);
ComplaintEntity savedComplaint = complaintDao.save(complaintEntity);
return savedComplaint.getComplaintId();
}

private ComplaintEntity convertBeanToEntity(ComplaintBean complaintBean) {


ComplaintEntity complaintEntity = new ComplaintEntity();
BeanUtils.copyProperties(complaintBean, complaintEntity);
return complaintEntity;
}
`

Why?

`BeanUtils.copyProperties()` ensures seamless conversion from `ComplaintBean` to


`ComplaintEntity`.
`complaintDao.save(complaintEntity)` persists the data into the database.

Effect

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/24
This method allows the registration of customer complaints, enabling issue tracking.

To-Do Item 1.4: Retrieve Complaint Details by Date Range

Task

Retrieve complaints within a date range using JPA EntityManager.

Solution

Modify the method:

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


Query query = manager.createQuery(
"SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWEEN :fromDate AND :toDate"
);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);

List<ComplaintEntity> entityList = query.getResultList();


List<ComplaintBean> beanList = new ArrayList<>();

for (ComplaintEntity complaintEntity : entityList) {


beanList.add(convertEntityToBean(complaintEntity));
}
return beanList;
}

private ComplaintBean convertEntityToBean(ComplaintEntity complaintEntity) {


ComplaintBean bean = new ComplaintBean();
BeanUtils.copyProperties(complaintEntity, bean);
return bean;
}
`

Why?

EntityManager is useful when custom JPQL queries are needed.


`query.setParameter("fromDate", fromDate)` ensures type safety and prevents SQL injection.

Effect

Helps in filtering complaints by date for audit and analysis.

To-Do Item 1.5: Retrieve All Complaint Types

Task

Fetch all complaint types using Spring JPA Data.

Solution

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/24
java

`public List<ComplaintTypeBean> getAllComplaintTypes() {


List<ComplaintTypeEntity> entityList = complaintTypeDao.findAll();
List<ComplaintTypeBean> beanList = new ArrayList<>();

for (ComplaintTypeEntity complaintTypeEntity : entityList) {


beanList.add(convertComplaintTypeEntityToBean(complaintTypeEntity));
}
return beanList;
}

private ComplaintTypeBean convertComplaintTypeEntityToBean(ComplaintTypeEntity complaintTypeEntity)


ComplaintTypeBean complaintTypeBean = new ComplaintTypeBean();
BeanUtils.copyProperties(complaintTypeEntity, complaintTypeBean);
return complaintTypeBean;
}
`

Effect

Simplifies fetching of complaint types, ensuring easy dropdown population in forms.

To-Do Item 1.6: Prevent Duplicate Complaints

Task

Before registering a complaint, check if the customer already submitted a complaint of the same
type.

Solution

java

`public int registerComplaintDetails(ComplaintBean complaintBean) throws Exception {


int count = complaintDaoWrapper.getCustomerByComplaintType(
complaintBean.getCustomerName(), complaintBean.getComplaintTypeId()
);
if (count == 1) {
throw new Exception("Customer has already submitted a complaint with the same type.");
}
return complaintDaoWrapper.registerComplaintDetails(complaintBean);
}
`

Effect

Prevents duplicate complaints, improving data consistency.

To-Do Item 1.7: Retrieve Complaint Details by Date Range

Task

Call `complaintDaoWrapper.getComplaintDetailsByDate()` to fetch complaints within a date range.

Solution

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/24
java

`@Override
public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {
return complaintDaoWrapper.getComplaintDetailsByDate(fromDate, toDate);
}
`

To-Do Item 1.8: Retrieve All Complaint Types as a Map

Solution

java

`@Override
public Map<Integer, String> getAllComplaintTypes() {
Map<Integer, String> map = new HashMap<>();
List<ComplaintTypeBean> beanList = complaintDaoWrapper.getAllComplaintTypes();

for (ComplaintTypeBean bean : beanList) {


map.put(bean.getComplaintTypeId(), bean.getComplaintTypeName());
}
return map;
}
`

Effect

Efficiently maps complaint type IDs to names for dropdown selection.

To-Do Item 1.9: Process Complaint Form

Solution

java

`@RequestMapping(value = "/complaintForm.html")
public ModelAndView processComplaintForm(@ModelAttribute("complaintBean") @Valid ComplaintBean compl
BindingResult result) throws Exception {
ModelAndView modelAndView = new ModelAndView();
if (result.hasErrors()) {
modelAndView.setViewName("ComplaintPage");
return modelAndView;
}
int id = complaintService.registerComplaintDetails(complaintBean);
modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() + ", your complaint is
modelAndView.setViewName("Success");
return modelAndView;
}
`

Effect

Displays success messages dynamically.

To-Do Item 1.12: Spring MVC Standard Validation


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/24
Solution

java

`@NotBlank(message = "Please Enter Customer Name")


private String customerName;

@Past(message = "Date of Incidence must be a past date")


@DateTimeFormat(pattern = "dd-MMM-yyyy")
private Date dateOfIncidence;
`

Effect

Ensures proper form validation.

This covers all the To-Do items in detail! Let me know if you need any clarifications. 🚀
Flow of the Program (Spring Boot Complaint Management System)

The program follows a layered architecture, where different components handle different
responsibilities. The key layers are:

1. Controller Layer (Handles HTTP Requests)


2. Service Layer (Business Logic)
3. DAO (Data Access) Layer (Database Interactions)
4. Entity Layer (Database Representation)
5. View Layer (User Interface)

1️⃣ High-Level Flow


1. A user submits a complaint through a web form.
2. The request goes to the Spring MVC Controller, which processes it.
3. The controller calls the Service Layer, which contains the business logic.
4. The Service Layer checks for duplicate complaints and calls the DAO Layer to store/retrieve data.
5. The DAO Layer interacts with the Database via JPA/Hibernate.
6. Once the complaint is registered successfully, a success message is displayed to the user.

2️⃣ Detailed Request Flow


📌 Step 1: User Submits a Complaint
The user fills out a complaint form and submits it.
The request is handled by a Spring MVC Controller.

java

`@RequestMapping(value = "/complaintForm.html")
public ModelAndView processComplaintForm(@ModelAttribute("complaintBean") @Valid ComplaintBean compl
BindingResult result) throws Exception {
ModelAndView modelAndView = new ModelAndView();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/24
// Validate input fields
if (result.hasErrors()) {
modelAndView.setViewName("ComplaintPage");
return modelAndView;
}

// Call Service Layer to register complaint


int id = complaintService.registerComplaintDetails(complaintBean);

// Send success message to the view


modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() + ", your complaint is
modelAndView.setViewName("Success");
return modelAndView;
}
`

What happens here?

The form data is bound to `ComplaintBean`.


Validation is performed using annotations like `@NotBlank`, `@Past`, etc.
If validation fails → The user stays on the ComplaintPage.
If validation succeeds → The complaint is processed by the Service Layer.

📌 Step 2: Service Layer Processes Complaint


The Service Layer contains business logic.
It checks if the customer already submitted a complaint of the same type.
If it's a duplicate complaint, an exception is thrown.
Otherwise, the complaint is stored in the database.

java

`public int registerComplaintDetails(ComplaintBean complaintBean) throws Exception {


int count = complaintDaoWrapper.getCustomerByComplaintType(
complaintBean.getCustomerName(), complaintBean.getComplaintTypeId()
);

if (count == 1) {
throw new Exception("Customer has already submitted a complaint with the same type.");
}

return complaintDaoWrapper.registerComplaintDetails(complaintBean);
}
`

What happens here?

Calls `getCustomerByComplaintType()` to check for duplicate complaints.


If a duplicate exists → Throws an exception.
Otherwise → Calls the DAO Layer to save the complaint.

📌 Step 3: DAO Layer Saves Complaint to Database


The DAO Layer uses Spring Data JPA to interact with the database.
The EntityManager or `complaintDao.save()` is used for persistence.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/24
java

`public int registerComplaintDetails(ComplaintBean complaintBean) {


ComplaintEntity complaintEntity = convertBeanToEntity(complaintBean);
ComplaintEntity savedComplaint = complaintDao.save(complaintEntity);
return savedComplaint.getComplaintId();
}
`

What happens here?

Converts `ComplaintBean` into `ComplaintEntity`.


Saves the entity in the database using JPA.
Returns the Complaint ID.

📌 Step 4: Confirmation is Sent to the User


The Controller Layer receives a confirmation.
A success message is displayed on the web page.

java

`modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() + ", your complaint is su


`

The user sees a message like:

Hi John, your complaint is successfully registered.

3️⃣ Complaint Retrieval Flow


Users can retrieve complaints based on the date range.

📌 Step 1: User Requests Complaints by Date


The controller method handles the request.

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


return complaintDaoWrapper.getComplaintDetailsByDate(fromDate, toDate);
}
`

📌 Step 2: Service Layer Calls DAO


The Service Layer forwards the request to the DAO.

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


Query query = manager.createQuery(
"SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWEEN :fromDate AND :toDate"
);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/24
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);

List<ComplaintEntity> entityList = query.getResultList();


List<ComplaintBean> beanList = new ArrayList<>();

for (ComplaintEntity complaintEntity : entityList) {


beanList.add(convertEntityToBean(complaintEntity));
}

return beanList;
}
`

📌 Step 3: DAO Queries the Database


Retrieves complaints where `dateOfIncidence` is between `fromDate` and `toDate`.
Converts the ComplaintEntity objects into ComplaintBean.
Returns the list of complaints.

4️⃣ Complaint Types Retrieval Flow


A user can view all complaint types (like "Billing Issue", "Service Delay", etc.).

📌 Step 1: Service Layer Calls DAO


java

`public List<ComplaintTypeBean> getAllComplaintTypes() {


List<ComplaintTypeEntity> entityList = complaintTypeDao.findAll();
List<ComplaintTypeBean> beanList = new ArrayList<>();

for (ComplaintTypeEntity complaintTypeEntity : entityList) {


beanList.add(convertComplaintTypeEntityToBean(complaintTypeEntity));
}
return beanList;
}
`

📌 Step 2: DAO Fetches Data


java

`@Repository
public interface ComplaintTypeDao extends JpaRepository<ComplaintTypeEntity, Integer> {
}
`

Spring Data JPA automatically generates the `findAll()` method.


Retrieves all complaint types from the database.
Converts them into `ComplaintTypeBean` and returns them.

5️⃣ Exception Handling


If any errors occur, they are handled at the Service Layer and passed to the controller.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/24
java

`@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView modelAndView = new ModelAndView("ErrorPage");
modelAndView.addObject("errorMessage", e.getMessage());
return modelAndView;
}
`

What happens here?

If an error occurs (e.g., duplicate complaints), the user is redirected to an error page.

6️⃣ Summary of the Flow


Step Action Handled By

1️⃣ User submits a complaint Controller (`processComplaintForm`)


2️⃣ Validates input Controller (`@Valid ComplaintBean`)
3️⃣ Checks for duplicates Service (`registerComplaintDetails`)

4️⃣ Saves complaint to DB DAO (`complaintDao.save`)


5️⃣ Returns success message Controller (`modelAndView.addObject`)
6️⃣ User requests complaints by date Controller (`getComplaintDetailsByDate`)
7️⃣ Retrieves data from DB DAO (`findByDateRange`)

8️⃣ Returns complaints list Controller (`modelAndView.addObject`)

7️⃣ Conclusion
Spring MVC handles form submissions.
Service Layer ensures business logic (duplicate check, validation).
DAO Layer interacts with the database via Spring Data JPA.
JPQL queries help in filtering complaints.
Exception Handling ensures smooth user experience.

This modular approach keeps the application scalable and maintainable! 🚀


Detailed Code Execution Flow in Spring Boot Complaint
Management System
The Complaint Management System follows a layered architecture with key components:

1. Controller Layer – Handles HTTP requests.


2. Service Layer – Implements business logic.
3. DAO (Data Access) Layer – Interacts with the database.
4. Entity Layer – Maps database tables to Java objects.
5. View Layer – Displays results to users.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/24
Step-by-Step Execution Flow
Let's break down how the system works when a user submits a complaint.

📌 Step 1: User Fills Complaint Form


The user accesses the web application and fills in a complaint form.
Fields like:
Customer Name
Complaint Type
Date of Incidence
Description
The user clicks the Submit button.

Example HTML Form:

html

`<form action="/complaintForm.html" method="post">


<label for="customerName">Name:</label>
<input type="text" name="customerName" required>

<label for="complaintTypeId">Complaint Type:</label>


<select name="complaintTypeId">
<option value="1">Billing Issue</option>
<option value="2">Service Delay</option>
</select>

<label for="dateOfIncidence">Date:</label>
<input type="date" name="dateOfIncidence" required>

<input type="submit" value="Submit">


</form>
`

When the user submits the form, a POST request is sent to `/complaintForm.html`.

📌 Step 2: Controller Receives Request


The Controller Layer handles the request and binds form data to a Java object.

java

`@RequestMapping(value = "/complaintForm.html")
public ModelAndView processComplaintForm(
@ModelAttribute("complaintBean") @Valid ComplaintBean complaintBean,
BindingResult result) throws Exception {

ModelAndView modelAndView = new ModelAndView();

// 1️⃣Validate form data


if (result.hasErrors()) {
modelAndView.setViewName("ComplaintPage");
return modelAndView;
}

// 2️⃣Send data to Service Layer for processing


int id = complaintService.registerComplaintDetails(complaintBean);

// 3️⃣ Display success message


modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() +

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/24
", your complaint is successfully registered.");
modelAndView.setViewName("Success");

return modelAndView;
}
`

Breakdown:

1. Spring binds form data (`@ModelAttribute ComplaintBean complaintBean`).


2. Validation is performed (`@Valid` ensures the form fields meet constraints).
3. If validation fails → User remains on `ComplaintPage.html`.
4. If validation succeeds → Calls the Service Layer (`complaintService.registerComplaintDetails()`).
5. Success message is returned → Redirects to `Success.html`.

📌 Step 3: Service Layer Processes Complaint


The Service Layer contains business logic.

java

// 1️⃣
`public int registerComplaintDetails(ComplaintBean complaintBean) throws Exception {
Check if the customer already has the same complaint type
int count = complaintDaoWrapper.getCustomerByComplaintType(
complaintBean.getCustomerName(), complaintBean.getComplaintTypeId()
);

if (count == 1) {
throw new Exception("Customer has already submitted a complaint with the same type.");
}

// 2️⃣Save complaint to the database


return complaintDaoWrapper.registerComplaintDetails(complaintBean);
}
`

Breakdown:

1. Calls `getCustomerByComplaintType()` to check if the user already submitted the same complaint
type.
2. If duplicate exists → Throws an exception (`Customer has already submitted a complaint`).
3. If no duplicate exists → Calls the DAO layer to store complaint in the database.

📌 Step 4: DAO Layer Stores Complaint


The DAO (Data Access Object) interacts with the database.

java

`public int registerComplaintDetails(ComplaintBean complaintBean) {


// Convert Bean to Entity
ComplaintEntity complaintEntity = convertBeanToEntity(complaintBean);

// Save to database
ComplaintEntity savedComplaint = complaintDao.save(complaintEntity);

return savedComplaint.getComplaintId();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/24
}
`

Breakdown:

1. Converts the ComplaintBean (Java object) into a ComplaintEntity (database entity).


2. Saves it in the database using JPA (`complaintDao.save()`).
3. Returns the Complaint ID after successful insertion.

📌 Step 5: Confirmation Sent to User


Once the database stores the complaint, the user is shown a success message.

java

`modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() +


", your complaint is successfully registered.");
`

This message is displayed in `Success.html`.

Example Output:

Hi John, your complaint is successfully registered.

📌 Retrieving Complaints by Date


Users can search complaints based on a date range.

Step 1: Controller Handles Request

java

`@RequestMapping("/getComplaintsByDate")
public ModelAndView getComplaintsByDate(@RequestParam Date fromDate, @RequestParam Date toDate) {
List<ComplaintBean> complaints = complaintService.getComplaintDetailsByDate(fromDate, toDate);

ModelAndView modelAndView = new ModelAndView("ComplaintListPage");


modelAndView.addObject("complaints", complaints);
return modelAndView;
}
`

The user enters From Date and To Date.


The controller calls the Service Layer.

Step 2: Service Layer Calls DAO

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


return complaintDaoWrapper.getComplaintDetailsByDate(fromDate, toDate);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/24
}
`

Step 3: DAO Queries Database

java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


Query query = manager.createQuery(
"SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWEEN :fromDate AND :toDate"
);

query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);

List<ComplaintEntity> entityList = query.getResultList();


List<ComplaintBean> beanList = new ArrayList<>();

for (ComplaintEntity complaintEntity : entityList) {


beanList.add(convertEntityToBean(complaintEntity));
}

return beanList;
}
`

Breakdown:

1. Uses JPQL Query to fetch complaints between `fromDate` and `toDate`.


2. Converts ComplaintEntity objects into ComplaintBean.
3. Returns the list of complaints to the controller.
4. The controller sends the list to ComplaintListPage.html.

📌 Error Handling
If an error occurs, it is caught using a Global Exception Handler.

java

`@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView modelAndView = new ModelAndView("ErrorPage");
modelAndView.addObject("errorMessage", e.getMessage());
return modelAndView;
}
`

If the user submits a duplicate complaint, they are redirected to an Error Page.

📌 Final Flow Summary


Step Action Handled By
1️⃣ User fills out complaint form HTML form
2️⃣ Form is submitted Controller (`processComplaintForm`)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/24
Step Action Handled By
3️⃣ Controller calls Service Layer ComplaintService

4️⃣ Service checks for duplicates ComplaintDaoWrapper


5️⃣ If unique, saves in DB ComplaintDao.save()
6️⃣ User sees success message Success.html
7️⃣ User requests complaints by date Controller (`getComplaintsByDate`)

8️⃣ DAO fetches complaints from DB JPQL Query


9️⃣ Complaints displayed on page ComplaintListPage.html

This layered architecture ensures clean separation of concerns, making the system scalable and
maintainable! 🚀
Complaint Management System - Detailed Explanation
The Complaint Management System is a Spring Boot web application that allows users to submit,
track, and manage complaints efficiently. It follows a layered architecture for clean separation of
concerns and scalability.

🔹 Features of the System


📝 User Features
✔ Register a complaint with details like customer name, complaint type, date of incidence, and
description.
✔ View submitted complaints by entering a date range.
✔ Receive confirmation messages for successful complaint submission.
✔ Error handling for duplicate complaints and invalid inputs.
👨‍💼 Admin Features
✔ Search complaints based on date range.
✔ View all complaints stored in the system.
✔ Manage complaints through a centralized interface.
🔹 Technology Stack
Technology Purpose

Java (JDK 11/17) Backend logic


Spring Boot Main framework
Spring MVC Handles HTTP requests

Spring Data JPA Database interaction


Hibernate ORM (Object-Relational Mapping)
MySQL / PostgreSQL Database
Thymeleaf / JSP Frontend UI

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/24
Technology Purpose
Lombok Reduces boilerplate code

Maven Dependency management


Tomcat Embedded web server

🔹 Project Architecture
The project follows the 3-Tier Architecture:
1️⃣ Controller Layer (Presentation) → Handles user requests.
2️⃣ Service Layer (Business Logic) → Processes and validates data.
3️⃣ DAO Layer (Persistence) → Interacts with the database.
🔹 Entity Layer → Maps Java objects to database tables.
🔹 View Layer → Displays UI pages to users.
🔹 Project Flow (Step-by-Step)
📌 1. User Registers a Complaint
The user fills in customer name, complaint type, date, and description.
Submits the form using POST request to `/complaintForm.html`.
The Controller receives data, validates it, and forwards it to the Service Layer.

Example Complaint Form (Frontend - HTML)

html

`<form action="/complaintForm.html" method="post">


<label for="customerName">Name:</label>
<input type="text" name="customerName" required>

<label for="complaintTypeId">Complaint Type:</label>


<select name="complaintTypeId">
<option value="1">Billing Issue</option>
<option value="2">Service Delay</option>
</select>

<label for="dateOfIncidence">Date:</label>
<input type="date" name="dateOfIncidence" required>

<input type="submit" value="Submit">


</form>
`

📌 2. Controller Handles the Complaint Submission


The controller processes the form submission.

java

`@RequestMapping(value = "/complaintForm.html")
public ModelAndView processComplaintForm(
@ModelAttribute("complaintBean") @Valid ComplaintBean complaintBean,
BindingResult result) throws Exception {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/24
ModelAndView modelAndView = new ModelAndView();

// 🛑 Validation Check
if (result.hasErrors()) {
modelAndView.setViewName("ComplaintPage");
return modelAndView;
}

// ✅ Forward to Service Layer


int id = complaintService.registerComplaintDetails(complaintBean);

// 🎉 Success Message
modelAndView.addObject("message", "Hi " + complaintBean.getCustomerName() +
", your complaint is successfully registered.");
modelAndView.setViewName("Success");

return modelAndView;
}
`

👉 Flow Explanation: 1️⃣ Extracts data from form submission ( `@ModelAttribute ComplaintBean
).
2️⃣ Validates form data (
complaintBean`
).
3️⃣ Calls Service Layer (
`@Valid`
`complaintService.registerComplaintDetails()`).
4️⃣ Returns success message to .
`Success.html`

📌 3. Service Layer Processes Complaint


java

// 🔍
`public int registerComplaintDetails(ComplaintBean complaintBean) throws Exception {
Check if the user already submitted the same complaint
int count = complaintDaoWrapper.getCustomerByComplaintType(
complaintBean.getCustomerName(), complaintBean.getComplaintTypeId()
);

if (count == 1) {
throw new Exception("Customer has already submitted a complaint with the same type.");
}

// ✅ Save Complaint
return complaintDaoWrapper.registerComplaintDetails(complaintBean);
}
`

👉 Flow Explanation: 1️⃣ Checks for duplicate complaints in the database.


2️⃣ If duplicate exists, throws an exception.
3️⃣ If unique, calls DAO Layer to save the complaint.
📌 4. DAO Layer Stores Complaint in the Database
java

`public int registerComplaintDetails(ComplaintBean complaintBean) {


// Convert Bean to Entity
ComplaintEntity complaintEntity = convertBeanToEntity(complaintBean);

// Save to database
ComplaintEntity savedComplaint = complaintDao.save(complaintEntity);

return savedComplaint.getComplaintId();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/24
}
`

👉 Flow Explanation: 1️⃣ Converts to `ComplaintEntity`.


2️⃣ Saves it using
`ComplaintBean`
.
3️⃣ Returns the generated Complaint ID.
`complaintDao.save()`

📌 5. User Views Complaints Based on Date


Users can search complaints by date range.
Controller:

java

`@RequestMapping("/getComplaintsByDate")
public ModelAndView getComplaintsByDate(@RequestParam Date fromDate, @RequestParam Date toDate) {
List<ComplaintBean> complaints = complaintService.getComplaintDetailsByDate(fromDate, toDate);

ModelAndView modelAndView = new ModelAndView("ComplaintListPage");


modelAndView.addObject("complaints", complaints);
return modelAndView;
}
`

📌 6. DAO Fetches Complaints from Database


java

`public List<ComplaintBean> getComplaintDetailsByDate(Date fromDate, Date toDate) {


Query query = manager.createQuery(
"SELECT c FROM ComplaintEntity c WHERE c.dateOfIncidence BETWEEN :fromDate AND :toDate"
);

query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);

List<ComplaintEntity> entityList = query.getResultList();


List<ComplaintBean> beanList = new ArrayList<>();

for (ComplaintEntity complaintEntity : entityList) {


beanList.add(convertEntityToBean(complaintEntity));
}

return beanList;
}
`

📌 7. Error Handling
If any error occurs, an Exception Handler displays a custom error message.

java

`@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e) {
ModelAndView modelAndView = new ModelAndView("ErrorPage");
modelAndView.addObject("errorMessage", e.getMessage());
return modelAndView;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/24
}
`

🔹 Database Design (MySQL Schema)


sql

`CREATE TABLE complaints (


complaint_id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
complaint_type_id INT NOT NULL,
date_of_incidence DATE NOT NULL,
description TEXT
);
`

🔹 Summary of System Flow


Step Action Handled By
1️⃣ User fills complaint form Frontend (HTML, JSP, Thymeleaf)
2️⃣ Form submitted via POST Controller (`processComplaintForm`)
3️⃣ Controller calls Service Layer ComplaintService
4️⃣ Service checks for duplicates ComplaintDaoWrapper
5️⃣ If unique, saves in DB ComplaintDao.save()

6️⃣ User sees success message Success.html


7️⃣ User searches complaints by date Controller (`getComplaintsByDate`)
8️⃣ DAO fetches complaints from DB JPQL Query
9️⃣ Complaints displayed in UI ComplaintListPage.html

This layered architecture makes the system efficient, scalable, and maintainable! 🚀

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/24

You might also like