Online Banking System using Java and MySQL

Rashmi Mishra
0

 

Online Banking System 

using Java and MySQL

Creating an Online Banking System using Java and MySQL is a great project to learn about web development, databases, and security. Here’s a beginner-friendly, step-by-step guide to help you get started. This guide will walk you through setting up the project, implementing features like account management, transactions, fund transfers, secure login, and multi-factor authentication.

Step-by-Step Guide

Step 1: Set Up Your Development Environment

  1. Install JDK:
    • Download and install the Java Development Kit (JDK) from the Oracle website or adopt OpenJDK.
    • Set the JAVA_HOME environment variable.
  2. Install an IDE:
    • Download and install an Integrated Development Environment (IDE) like Eclipse or IntelliJ IDEA.
  3. Install MySQL:
    • Download and install MySQL Server from the MySQL website.
    • Use MySQL Workbench or any other client to manage your databases.
  4. Install Maven:
    • Maven is a build automation tool for Java projects. Download and install Maven from the Apache Maven website.

Step 2: Create a New Spring Boot Project

  1. Create a Spring Boot Project:
    • Use Spring Initializr to generate a new Spring Boot project.
      • Choose Maven Project.
      • Select Java and the appropriate Spring Boot version.
      • Add dependencies:
        • Spring Web
        • Spring Data JPA
        • MySQL Driver
        • Spring Security
      • Click Generate to download the project.
  2. Import the Project into Your IDE:
    • Open your IDE and import the downloaded Spring Boot project.

Step 3: Configure Database Connection

  1. Open application.properties:
    • Navigate to src/main/resources/application.properties and configure your database settings:

spring.datasource.url=jdbc:mysql://localhost:3306/online_banking

spring.datasource.username=root

spring.datasource.password=your_password

spring.jpa.hibernate.ddl-auto=update

  1. Create the Database:
    • Open MySQL Workbench and create a new database named online_banking:

CREATE DATABASE online_banking;

DATABASE TABLES

For the Online Banking System project, you'll need several tables to manage users, accounts, transactions, and any additional features you might want to implement (like multi-factor authentication). Here’s a list of the key tables along with their structures:

1. users Table

Stores information about each user.

Column Name

Data Type

Constraints

id

BIGINT

PRIMARY KEY, AUTO_INCREMENT

name

VARCHAR(100)

NOT NULL

email

VARCHAR(100)

NOT NULL, UNIQUE

password

VARCHAR(255)

NOT NULL

roles

JSON

NOT NULL

created_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

updated_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

2. accounts Table

Stores account information for each user.

Column Name

Data Type

Constraints

id

BIGINT

PRIMARY KEY, AUTO_INCREMENT

balance

DECIMAL(15, 2)

DEFAULT 0.00

user_id

BIGINT

NOT NULL, FOREIGN KEY REFERENCES users(id) ON DELETE CASCADE

created_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

updated_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

3. transactions Table

Stores transaction records for each account.

Column Name

Data Type

Constraints

id

BIGINT

PRIMARY KEY, AUTO_INCREMENT

amount

DECIMAL(15, 2)

NOT NULL

type

ENUM('DEPOSIT', 'WITHDRAWAL', 'TRANSFER')

NOT NULL

date

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

account_id

BIGINT

NOT NULL, FOREIGN KEY REFERENCES accounts(id) ON DELETE CASCADE

created_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

updated_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

4. multi_factor_auth Table

(Optional) Stores multi-factor authentication details for users.

Column Name

Data Type

Constraints

id

BIGINT

PRIMARY KEY, AUTO_INCREMENT

user_id

BIGINT

NOT NULL, FOREIGN KEY REFERENCES users(id) ON DELETE CASCADE

auth_code

VARCHAR(10)

NOT NULL

is_verified

BOOLEAN

DEFAULT FALSE

created_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

updated_at

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

5. audit_logs Table

(Optional) Stores logs of user actions (for tracking purposes).

Column Name

Data Type

Constraints

id

BIGINT

PRIMARY KEY, AUTO_INCREMENT

user_id

BIGINT

NOT NULL, FOREIGN KEY REFERENCES users(id) ON DELETE CASCADE

action

VARCHAR(255)

NOT NULL

timestamp

TIMESTAMP

DEFAULT CURRENT_TIMESTAMP

Example SQL to Create Tables

CREATE TABLE users (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(100) NOT NULL,

    email VARCHAR(100) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    roles JSON NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

);

 

CREATE TABLE accounts (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    balance DECIMAL(15, 2) DEFAULT 0.00,

    user_id BIGINT NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

);

 

CREATE TABLE transactions (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    amount DECIMAL(15, 2) NOT NULL,

    type ENUM('DEPOSIT', 'WITHDRAWAL', 'TRANSFER') NOT NULL,

    date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    account_id BIGINT NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE

);

 

CREATE TABLE multi_factor_auth (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    user_id BIGINT NOT NULL,

    auth_code VARCHAR(10) NOT NULL,

    is_verified BOOLEAN DEFAULT FALSE,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

);

 

CREATE TABLE audit_logs (

    id BIGINT AUTO_INCREMENT PRIMARY KEY,

    user_id BIGINT NOT NULL,

    action VARCHAR(255) NOT NULL,

    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE

);

Conclusion

These tables form the backbone of your Online Banking System. You can expand this structure as needed by adding more tables or columns for additional features.


Project Directory Structure

online-banking-system/

── src/

   ── main/

      ── java/

         └── com/

             └── banking/

                 ── config/

                    └── SecurityConfig.java

                 ── controller/

                    ── AuthController.java

                    ── AccountController.java

                    └── TransactionController.java

                 ── model/

                    ── User.java

                    ── Account.java

                    └── Transaction.java

                    └── MultiFactorAuth.java   *(if implemented)*

                 ── repository/

                    ── UserRepository.java

                    ── AccountRepository.java

                    └── TransactionRepository.java

                 ── service/

                    ── UserService.java

                    ── AccountService.java

                    └── TransactionService.java

                 └── OnlineBankingSystemApplication.java

      └── resources/

          ── application.properties

          └── static/                       *(for static resources like HTML, CSS, JS)*

          └── templates/                    *(for Thymeleaf templates if used)*

          └── log4j2.xml                     *(for logging configuration)*

   └── test/

       └── java/

           └── com/

               └── banking/

                   └── OnlineBankingSystemApplicationTests.java

── pom.xml                                  *(if using Maven)*

└── README.md

File Descriptions

  1. src/main/java/com/banking/OnlineBankingSystemApplication.java
    • The main entry point of the Spring Boot application.
  2. src/main/java/com/banking/config/SecurityConfig.java
    • Contains security configurations, including Spring Security settings.
  3. Controllers:
    • src/main/java/com/banking/controller/AuthController.java
      • Manages authentication and user registration.
    • src/main/java/com/banking/controller/AccountController.java
      • Handles account-related operations.
    • src/main/java/com/banking/controller/TransactionController.java
      • Manages transactions.
  4. Models:
    • src/main/java/com/banking/model/User.java
      • Represents the user entity.
    • src/main/java/com/banking/model/Account.java
      • Represents the account entity.
    • src/main/java/com/banking/model/Transaction.java
      • Represents the transaction entity.
    • src/main/java/com/banking/model/MultiFactorAuth.java (optional)
      • Represents multi-factor authentication details for users.
  5. Repositories:
    • src/main/java/com/banking/repository/UserRepository.java
      • Handles database operations related to users.
    • src/main/java/com/banking/repository/AccountRepository.java
      • Handles database operations related to accounts.
    • src/main/java/com/banking/repository/TransactionRepository.java
      • Handles database operations related to transactions.
  6. Services:
    • src/main/java/com/banking/service/UserService.java
      • Contains business logic for user-related operations.
    • src/main/java/com/banking/service/AccountService.java
      • Contains business logic for account-related operations.
    • src/main/java/com/banking/service/TransactionService.java
      • Contains business logic for transaction-related operations.
  7. src/main/resources/application.properties
    • Configuration file for application properties, including database connection settings.
  8. src/main/resources/static/
    • This directory can hold static resources like CSS, JavaScript, and images.
  9. src/main/resources/templates/
    • If you use a template engine (like Thymeleaf), you can place your HTML files here.
  10. src/main/resources/log4j2.xml
    • Configuration file for logging (if using Log4j2 for logging).
  11. src/test/java/com/banking/OnlineBankingSystemApplicationTests.java
    • Contains unit tests for your application.
  12. pom.xml (if using Maven)
    • The Maven project file, containing dependencies and project information.
  13. README.md
    • Documentation for your project, including setup instructions and usage.

Conclusion

This structure should help you get started on your Online Banking System project. Each file serves a specific purpose, keeping the project organized and maintainable. You can expand upon this structure as your project grows or as you implement additional features.

Step 4: Create Entity Models

  1. Create User Entity:
    • Create a new package model in src/main/java/com/banking/.
    • Create a class User.java:
  1. Create Transaction Entity:
    • Create a class Transaction.java:

Step 5: Create Repositories

  1. Create UserRepository:
    • Create a package repository in src/main/java/com/banking/.
    • Create an interface UserRepository.java:
  1. Create TransactionRepository:
    • Create an interface TransactionRepository.java:

Step 6: Create Services

  1. Create UserService:
    • Create a package service in src/main/java/com/banking/.
    • Create a class UserService.java:
  1. Create AccountService:
    • Create a class AccountService.java:
  1. Create TransactionService:
    • Create a class TransactionService.java:

Step 7: Create Controllers

  1. Create AuthController:
    • Create a class AuthController.java:
  1. Create AccountController:
    • Create a class AccountController.java:
  1. Create TransactionController:
    • Create a class TransactionController.java:

Step 8: Implement Security

  1. Configure Spring Security:
    • Create a configuration class SecurityConfig.java:
  1. Implement Multi-Factor Authentication:
    • For simplicity, you can integrate an SMS or email verification service later to implement multi-factor authentication.

Step 9: Testing

  1. Run Your Application:
    • Use your IDE to run the Spring Boot application.
    • Open a web browser or API client (like Postman) to test your endpoints.
  2. Test Registration:
    • Send a POST request to /auth/register with a JSON body containing user details.
  3. Test Login:
    • Send a POST request to /auth/login with user credentials.
  4. Test Account Creation:
    • Send a POST request to /accounts with account details.
  5. Test Transactions:
    • Send a POST request to /transactions with transaction details.

Step 10: Further Development

  1. Implement Frontend:
    • Use frameworks like React, Angular, or Vue.js to create a user-friendly frontend.
  2. Add Features:
    • Implement additional features like password recovery, transaction history, and notifications.
  3. Deploy Your Application:
    • Once completed, consider deploying your application on platforms like Heroku, AWS, or DigitalOcean.

Conclusion

This guide provides a foundation for creating an Online Banking System using Java and MySQL. As you progress, you can enhance your application with more features, security, and a polished user interface.


CODE IN DETAILS 


SecurityConfig.java

This configuration will secure your application, manage user authentication, and set up basic authorization rules.

package com.banking.config;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import com.banking.service.UserService;

 @Configuration

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

     @Autowired

    private UserService userService;

 @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        // Set up authentication with the UserDetailsService

 auth.userDetailsService(userService).passwordEncoder(passwordEncoder());

    }

    @Bean

    @Override

    public AuthenticationManager authenticationManagerBean() throws Exception {

        return super.authenticationManagerBean();

    }

     @Bean

    public PasswordEncoder passwordEncoder() {

        // Use BCrypt for password encoding

        return new BCryptPasswordEncoder();

    }

     @Override

    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable() // Disable CSRF protection for simplicity (consider enabling in production)

            .authorizeRequests()

            .antMatchers("/auth/**").permitAll() // Allow public access to authentication endpoints

            .antMatchers("/api/**").authenticated() // Require authentication for all other endpoints

            .anyRequest().denyAll() // Deny all other requests

            .and()

            .formLogin() // Enable form-based authentication

            .loginPage("/auth/login") // Custom login page

            .permitAll()

            .and()

            .logout() // Enable logout functionality

            .logoutUrl("/auth/logout")

            .logoutSuccessUrl("/auth/login?logout") // Redirect after logout

            .permitAll();

    }

}

Explanation of the Configuration

  1. Class Annotations:
    • @Configuration: Indicates that this class contains Spring configuration.
    • @EnableWebSecurity: Enables Spring Security's web security support.
  2. Field Injection:
    • @Autowired private UserService userService;: Injects the UserService, which implements UserDetailsService to load user-specific data.
  3. Authentication Configuration:
    • configure(AuthenticationManagerBuilder auth): Configures the authentication manager to use the custom UserService for loading user data and specifies the password encoder (BCryptPasswordEncoder).
    • @Bean public AuthenticationManager authenticationManagerBean(): Exposes the AuthenticationManager as a bean, which is required for authentication in controllers.
  4. Password Encoder:
    • @Bean public PasswordEncoder passwordEncoder(): Returns a BCryptPasswordEncoder bean for encoding passwords securely.
  5. HTTP Security Configuration:
    • http.csrf().disable(): Disables CSRF protection (for development purposes). It's recommended to enable this in production environments.
    • .authorizeRequests(): Configures authorization for HTTP requests:
      • .antMatchers("/auth/**").permitAll(): Allows public access to any endpoint starting with /auth/.
      • .antMatchers("/api/**").authenticated(): Requires authentication for all API endpoints starting with /api/.
      • .anyRequest().denyAll(): Denies all other requests not explicitly allowed.
    • .formLogin(): Configures form-based authentication:
      • .loginPage("/auth/login"): Specifies a custom login page.
      • .permitAll(): Allows everyone to access the login page.
    • .logout(): Configures logout functionality:
      • .logoutUrl("/auth/logout"): Specifies the logout URL.
      • .logoutSuccessUrl("/auth/login?logout"): Redirects to the login page after a successful logout.

Conclusion

This SecurityConfig class sets up basic authentication and authorization for your Online Banking System. You can expand upon this by adding additional security features, such as multi-factor authentication or specific role-based access controls.

AuthController.java

 This controller will manage user authentication, including registration and login functionalities.

package com.banking.controller;

import com.banking.model.User;

import com.banking.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController

@RequestMapping("/auth")

public class AuthController {

    @Autowired

    private UserService userService;

    @Autowired

    private AuthenticationManager authenticationManager;

    @Autowired

    private PasswordEncoder passwordEncoder;

    @PostMapping("/register")

    public ResponseEntity<String> register(@Valid @RequestBody User user) {

        // Check if the email is already taken

        if (userService.existsByEmail(user.getEmail())) {

            return ResponseEntity.badRequest().body("Error: Email is already taken!");

        }

        // Encode the password before saving

        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userService.save(user); // Save the new user

        return ResponseEntity.ok("User registered successfully!");

    }

    @PostMapping("/login")

    public ResponseEntity<String> login(@RequestBody User loginUser) {

        try {

            // Authenticate the user

            Authentication authentication = authenticationManager.authenticate(

                    new UsernamePasswordAuthenticationToken(loginUser.getEmail(), loginUser.getPassword())

            );

            // If authentication is successful, you can generate a JWT or return a success message

            // Here, for simplicity, we'll just return a success message

            return ResponseEntity.ok("User logged in successfully!");

        } catch (AuthenticationException e) {

            return ResponseEntity.badRequest().body("Error: Invalid email or password!");

        }

    }

}

Explanation of the AuthController Class

  1. Class Annotations:
    • @RestController: Indicates that this class is a RESTful controller, handling HTTP requests and returning responses.
    • @RequestMapping("/auth"): Maps all request paths starting with /auth to this controller.
  2. Autowired Fields:
    • private UserService userService;: Injects the service for handling user-related operations (like registration and checking if an email exists).
    • private AuthenticationManager authenticationManager;: Injects the authentication manager to authenticate users.
    • private PasswordEncoder passwordEncoder;: Injects the password encoder for hashing passwords.
  3. Register Method:
    • Endpoint: POST /auth/register
    • Parameters: Accepts a User object in the request body.
    • Functionality:
      • Checks if the email already exists using userService.existsByEmail(user.getEmail()).
      • If the email is already taken, it returns a bad request response with an error message.
      • If the email is available, it encodes the password using passwordEncoder.encode(user.getPassword()) and saves the user using userService.save(user).
      • Returns a success message upon successful registration.
  4. Login Method:
    • Endpoint: POST /auth/login
    • Parameters: Accepts a User object containing the email and password in the request body.
    • Functionality:
      • Tries to authenticate the user with the provided email and password using the AuthenticationManager.
      • If authentication is successful, it returns a success message.
      • If authentication fails (invalid email or password), it catches the AuthenticationException and returns a bad request response with an error message.

Conclusion

The AuthController class provides endpoints for user registration and login in your Online Banking System. It ensures proper validation and security measures are in place. You can expand this controller with additional functionalities, such as password recovery or email verification, as needed.

AccountController.java

This controller will manage account-related operations, such as creating accounts, viewing account details, and transferring funds.

package com.banking.controller;

import com.banking.model.Account;

import com.banking.service.AccountService;

import com.banking.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.security.core.annotation.AuthenticationPrincipal;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/accounts")

public class AccountController {

    @Autowired

    private AccountService accountService;

    @Autowired

    private UserService userService;

    // Create a new account

    @PostMapping("/create")

    public ResponseEntity<String> createAccount(@RequestBody Account account, @AuthenticationPrincipal UserDetails userDetails) {

        String email = userDetails.getUsername();

        account.setUser(userService.findByEmail(email)); // Associate the account with the logged-in user

        accountService.save(account); // Save the new account

        return ResponseEntity.ok("Account created successfully!");

    }

    // Get all accounts for the logged-in user

    @GetMapping("/all")

    public ResponseEntity<List<Account>> getAllAccounts(@AuthenticationPrincipal UserDetails userDetails) {

        String email = userDetails.getUsername();

        List<Account> accounts = accountService.findByUserEmail(email); // Retrieve accounts associated with the user

        return ResponseEntity.ok(accounts);

    }

    // Get account details by account ID

    @GetMapping("/{accountId}")

    public ResponseEntity<Account> getAccountDetails(@PathVariable Long accountId) {

        Account account = accountService.findById(accountId);

        if (account != null) {

            return ResponseEntity.ok(account);

        } else {

            return ResponseEntity.notFound().build(); // Return 404 if account not found

        }

    }

    // Transfer funds between accounts

    @PostMapping("/transfer")

    public ResponseEntity<String> transferFunds(@RequestParam Long fromAccountId, @RequestParam Long toAccountId, @RequestParam double amount) {

        if (accountService.transferFunds(fromAccountId, toAccountId, amount)) {

            return ResponseEntity.ok("Funds transferred successfully!");

        } else {

            return ResponseEntity.badRequest().body("Error: Transfer failed. Please check the account details or balance.");

        }

    }

}

Explanation of the AccountController Class

  1. Class Annotations:
    • @RestController: Indicates that this class is a RESTful controller, handling HTTP requests and returning responses.
    • @RequestMapping("/api/accounts"): Maps all request paths starting with /api/accounts to this controller.
  2. Autowired Fields:
    • private AccountService accountService;: Injects the service responsible for handling account-related operations.
    • private UserService userService;: Injects the service for handling user-related operations.
  3. Create Account Method:
    • Endpoint: POST /api/accounts/create
    • Parameters: Accepts an Account object in the request body and uses @AuthenticationPrincipal UserDetails userDetails to get the logged-in user.
    • Functionality:
      • Associates the new account with the currently logged-in user using their email.
      • Calls accountService.save(account) to save the new account.
      • Returns a success message upon successful account creation.
  4. Get All Accounts Method:
    • Endpoint: GET /api/accounts/all
    • Parameters: Uses @AuthenticationPrincipal UserDetails userDetails to get the logged-in user's email.
    • Functionality:
      • Retrieves all accounts associated with the logged-in user using accountService.findByUserEmail(email).
      • Returns a list of accounts.
  5. Get Account Details Method:
    • Endpoint: GET /api/accounts/{accountId}
    • Parameters: Takes accountId as a path variable.
    • Functionality:
      • Calls accountService.findById(accountId) to retrieve the specified account.
      • Returns the account details if found, or a 404 Not Found response if not.
  6. Transfer Funds Method:
    • Endpoint: POST /api/accounts/transfer
    • Parameters: Accepts fromAccountId, toAccountId, and amount as request parameters.
    • Functionality:
      • Calls accountService.transferFunds(fromAccountId, toAccountId, amount) to transfer funds between accounts.
      • Returns a success message if the transfer is successful, or an error message if it fails (e.g., insufficient balance).

Conclusion

The AccountController class provides endpoints for managing accounts within your Online Banking System. It includes features for creating accounts, retrieving account details, and transferring funds between accounts. You can further enhance this controller by adding more features, such as updating account information or deleting accounts.

TransactionController.java

This controller will manage transaction-related operations, including viewing transaction history and creating new transactions.

package com.banking.controller;

import com.banking.model.Transaction;

import com.banking.service.TransactionService;

import com.banking.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

import org.springframework.security.core.annotation.AuthenticationPrincipal;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/api/transactions")

public class TransactionController {

    @Autowired

    private TransactionService transactionService;

    @Autowired

    private UserService userService;

    // View transaction history for the logged-in user

    @GetMapping("/history")

    public ResponseEntity<List<Transaction>> getTransactionHistory(@AuthenticationPrincipal UserDetails userDetails) {

        String email = userDetails.getUsername();

        List<Transaction> transactions = transactionService.findByUserEmail(email); // Retrieve transaction history for the user

        return ResponseEntity.ok(transactions);

    }

    // Create a new transaction

    @PostMapping("/create")

    public ResponseEntity<String> createTransaction(@RequestBody Transaction transaction, @AuthenticationPrincipal UserDetails userDetails) {

        String email = userDetails.getUsername();

        transaction.setUser(userService.findByEmail(email)); // Associate the transaction with the logged-in user

        transactionService.save(transaction); // Save the new transaction

        return ResponseEntity.ok("Transaction created successfully!");

    }

    // Get transaction details by transaction ID

    @GetMapping("/{transactionId}")

    public ResponseEntity<Transaction> getTransactionDetails(@PathVariable Long transactionId) {

        Transaction transaction = transactionService.findById(transactionId);

        if (transaction != null) {

            return ResponseEntity.ok(transaction);

        } else {

            return ResponseEntity.notFound().build(); // Return 404 if transaction not found

        }

    }

}

Explanation of the TransactionController Class

  1. Class Annotations:
    • @RestController: Indicates that this class is a RESTful controller, handling HTTP requests and returning responses.
    • @RequestMapping("/api/transactions"): Maps all request paths starting with /api/transactions to this controller.
  2. Autowired Fields:
    • private TransactionService transactionService;: Injects the service responsible for handling transaction-related operations.
    • private UserService userService;: Injects the service for handling user-related operations.
  3. Get Transaction History Method:
    • Endpoint: GET /api/transactions/history
    • Parameters: Uses @AuthenticationPrincipal UserDetails userDetails to get the logged-in user's email.
    • Functionality:
      • Calls transactionService.findByUserEmail(email) to retrieve the transaction history for the logged-in user.
      • Returns a list of transactions.
  4. Create Transaction Method:
    • Endpoint: POST /api/transactions/create
    • Parameters: Accepts a Transaction object in the request body and uses @AuthenticationPrincipal UserDetails userDetails to get the logged-in user.
    • Functionality:
      • Associates the new transaction with the currently logged-in user using their email.
      • Calls transactionService.save(transaction) to save the new transaction.
      • Returns a success message upon successful transaction creation.
  5. Get Transaction Details Method:
    • Endpoint: GET /api/transactions/{transactionId}
    • Parameters: Takes transactionId as a path variable.
    • Functionality:
      • Calls transactionService.findById(transactionId) to retrieve the specified transaction.
      • Returns the transaction details if found, or a 404 Not Found response if not.

Conclusion

The TransactionController class provides endpoints for managing transactions within your Online Banking System. It includes features for viewing transaction history, creating new transactions, and retrieving transaction details. You can further enhance this controller by adding more features, such as updating or deleting transactions. 

User.java

 This class represents the user entity and defines the properties and relationships relevant to users in your application.

package com.banking.model;

import javax.persistence.*;

import javax.validation.constraints.Email;

import javax.validation.constraints.NotBlank;

import javax.validation.constraints.Size;

import java.util.List;

@Entity

@Table(name = "users")

public class User {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    @NotBlank(message = "Name is mandatory")

    private String name;

    @Email(message = "Email should be valid")

    @NotBlank(message = "Email is mandatory")

    @Column(unique = true)

    private String email;

    @NotBlank(message = "Password is mandatory")

    @Size(min = 6, message = "Password should be at least 6 characters long")

    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

    private List<Account> accounts;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)

    private List<Transaction> transactions;

   // Constructors

    public User() {}

    public User(String name, String email, String password) {

        this.name = name;

        this.email = email;

        this.password = password;

    }

    // Getters and Setters

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public List<Account> getAccounts() {

        return accounts;

    }

    public void setAccounts(List<Account> accounts) {

        this.accounts = accounts;

    }

    public List<Transaction> getTransactions() {

        return transactions;

    }

    public void setTransactions(List<Transaction> transactions) {

        this.transactions = transactions;

    }

}

Explanation of the User Model Class

  1. Class Annotations:
    • @Entity: Marks this class as a JPA entity.
    • @Table(name = "users"): Specifies the name of the table in the database.
  2. Fields:
    • @Id: Marks the primary key of the entity.
    • @GeneratedValue(strategy = GenerationType.IDENTITY): Specifies that the ID should be generated automatically.
    • @NotBlank: Ensures that the field cannot be empty.
    • @Email: Validates that the email is in the correct format.
    • @Size(min = 6): Validates that the password is at least 6 characters long.
    • @Column(unique = true): Ensures that the email field is unique in the database.
  3. Relationships:
    • @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY):
      • This annotation defines a one-to-many relationship between User and Account, as well as User and Transaction.
      • mappedBy = "user" indicates that the User entity is not responsible for managing the relationship, which is handled by the Account and Transaction entities.
      • cascade = CascadeType.ALL specifies that all operations (like persist, remove, etc.) will be cascaded to associated accounts and transactions.
      • fetch = FetchType.LAZY ensures that associated accounts and transactions are loaded lazily (i.e., only when accessed).
  4. Constructors:
    • A no-argument constructor is provided for JPA.
    • A parameterized constructor is included for easier object creation.
  5. Getters and Setters:
    • Standard getters and setters for all fields to access and modify the user properties.

Conclusion

The User class is a crucial part of your Online Banking System, representing the user entity and its relationships with accounts and transactions. You can expand this model by adding more fields or methods as needed for your application. 

Account.java 

This class represents bank accounts and defines the properties and relationships relevant to accounts in your application.

package com.banking.model;

import javax.persistence.*;

import javax.validation.constraints.DecimalMin;

import javax.validation.constraints.NotBlank;

import javax.validation.constraints.NotNull;

import java.util.Date;

@Entity

@Table(name = "accounts")

public class Account {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    @NotBlank(message = "Account number is mandatory")

    @Column(unique = true)

    private String accountNumber;

    @NotNull(message = "Balance is mandatory")

    @DecimalMin(value = "0.0", message = "Balance must be positive")

    private double balance;

 @NotBlank(message = "Account type is mandatory")

    private String accountType; // e.g., Savings, Checking

    @Temporal(TemporalType.DATE)

    private Date createdAt;

    @Temporal(TemporalType.DATE)

    private Date updatedAt;

    @ManyToOne(fetch = FetchType.LAZY)

    @JoinColumn(name = "user_id", nullable = false)

    private User user; // Association with the User entity

    // Constructors

    public Account() {}

    public Account(String accountNumber, double balance, String accountType, User user) {

        this.accountNumber = accountNumber;

        this.balance = balance;

        this.accountType = accountType;

        this.user = user;

        this.createdAt = new Date();

        this.updatedAt = new Date();

    }

    // Getters and Setters

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getAccountNumber() {

        return accountNumber;

    }

    public void setAccountNumber(String accountNumber) {

        this.accountNumber = accountNumber;

    }

    public double getBalance() {

        return balance;

    }

    public void setBalance(double balance) {

        this.balance = balance;

    }

    public String getAccountType() {

        return accountType;

    }

    public void setAccountType(String accountType) {

        this.accountType = accountType;

    }

    public Date getCreatedAt() {

        return createdAt;

    }

    public void setCreatedAt(Date createdAt) {

        this.createdAt = createdAt;

    }

     public Date getUpdatedAt() {

        return updatedAt;

    }

     public void setUpdatedAt(Date updatedAt) {

        this.updatedAt = updatedAt;

    }

     public User getUser() {

        return user;

    }

     public void setUser(User user) {

        this.user = user;

    }

}

Explanation of the Account Model Class

  1. Class Annotations:
    • @Entity: Marks this class as a JPA entity.
    • @Table(name = "accounts"): Specifies the name of the table in the database.
  2. Fields:
    • @Id: Marks the primary key of the entity.
    • @GeneratedValue(strategy = GenerationType.IDENTITY): Specifies that the ID should be generated automatically.
    • @NotBlank: Ensures that the account number and account type cannot be empty.
    • @Column(unique = true): Ensures that the account number is unique in the database.
    • @NotNull: Ensures that the balance cannot be null.
    • @DecimalMin(value = "0.0"): Validates that the balance must be positive.
    • @Temporal: Specifies how to handle date values; in this case, both createdAt and updatedAt are of type Date.
  3. Relationships:
    • @ManyToOne(fetch = FetchType.LAZY): Defines a many-to-one relationship with the User entity.
    • @JoinColumn(name = "user_id", nullable = false): Specifies the foreign key column in the database for this relationship.
  4. Constructors:
    • A no-argument constructor is provided for JPA.
    • A parameterized constructor is included for easier object creation, allowing you to set the account number, balance, account type, and associated user.
  5. Getters and Setters:
    • Standard getters and setters for all fields to access and modify account properties.

Conclusion

The Account class is a key component of your Online Banking System, representing bank accounts and their attributes. You can expand this model by adding more fields or methods as needed for your application, such as methods for updating the balance or performing account-specific operations. 

Transaction.java 

This class represents financial transactions and defines the properties and relationships relevant to transactions in your application.

package com.banking.model;

 import javax.persistence.*;

import javax.validation.constraints.DecimalMin;

import javax.validation.constraints.NotNull;

import java.util.Date;

@Entity

@Table(name = "transactions")

public class Transaction {

     @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

     @NotNull(message = "Amount is mandatory")

    @DecimalMin(value = "0.01", message = "Amount must be positive")

    private double amount;

 @NotNull(message = "Transaction type is mandatory")

    private String transactionType; // e.g., Deposit, Withdraw, Transfer

    @Temporal(TemporalType.TIMESTAMP)

    private Date transactionDate;

    @ManyToOne(fetch = FetchType.LAZY)

    @JoinColumn(name = "user_id", nullable = false)

    private User user; // Association with the User entity

    @ManyToOne(fetch = FetchType.LAZY)

    @JoinColumn(name = "account_id", nullable = false)

    private Account account; // Association with the Account entity

     // Constructors

    public Transaction() {}

    public Transaction(double amount, String transactionType, User user, Account account) {

        this.amount = amount;

        this.transactionType = transactionType;

        this.user = user;

        this.account = account;

        this.transactionDate = new Date(); // Set current date and time

    }

 // Getters and Setters

    public Long getId() {

        return id;

    }

 public void setId(Long id) {

        this.id = id;

    }

 public double getAmount() {

        return amount;

    }

    public void setAmount(double amount) {

        this.amount = amount;

    }

    public String getTransactionType() {

        return transactionType;

    }

 public void setTransactionType(String transactionType) {

        this.transactionType = transactionType;

    }

    public Date getTransactionDate() {

        return transactionDate;

    }

    public void setTransactionDate(Date transactionDate) {

        this.transactionDate = transactionDate;

    }

    public User getUser() {

        return user;

    }

    public void setUser(User user) {

        this.user = user;

    }

    public Account getAccount() {

        return account;

    }

    public void setAccount(Account account) {

        this.account = account;

    }

}

Explanation of the Transaction Model Class

  1. Class Annotations:
    • @Entity: Marks this class as a JPA entity.
    • @Table(name = "transactions"): Specifies the name of the table in the database.
  2. Fields:
    • @Id: Marks the primary key of the entity.
    • @GeneratedValue(strategy = GenerationType.IDENTITY): Specifies that the ID should be generated automatically.
    • @NotNull: Ensures that the amount and transaction type cannot be null.
    • @DecimalMin(value = "0.01"): Validates that the transaction amount must be positive and at least 0.01.
    • @Temporal(TemporalType.TIMESTAMP): Specifies that the transaction date should store the date and time of the transaction.
  3. Relationships:
    • @ManyToOne(fetch = FetchType.LAZY): Defines a many-to-one relationship with the User entity.
    • @JoinColumn(name = "user_id", nullable = false): Specifies the foreign key column in the database for this relationship.
    • @ManyToOne(fetch = FetchType.LAZY): Defines a many-to-one relationship with the Account entity.
    • @JoinColumn(name = "account_id", nullable = false): Specifies the foreign key column in the database for this relationship.
  4. Constructors:
    • A no-argument constructor is provided for JPA.
    • A parameterized constructor is included for easier object creation, allowing you to set the amount, transaction type, associated user, and associated account. The transaction date is set to the current date and time.
  5. Getters and Setters:
    • Standard getters and setters for all fields to access and modify transaction properties.

Conclusion

The Transaction class is a crucial part of your Online Banking System, representing financial transactions and their attributes. You can expand this model by adding more fields or methods as needed, such as methods for validating transaction amounts or performing transaction-related operations. 

MultiFactorAuth.java

This class will handle the logic related to multi-factor authentication (MFA), ensuring that users can securely log in by providing an additional verification step after entering their credentials.

package com.banking.security;

 import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.util.Random;

@Service

public class MultiFactorAuth {

    @Autowired

    private UserDetailsService userDetailsService;

    @Autowired

    private PasswordEncoder passwordEncoder;

 // Generates a random verification code for MFA

    public String generateVerificationCode() {

        Random random = new Random();

        int code = 100000 + random.nextInt(900000); // Generate a 6-digit code

        return String.valueOf(code);

    }

 // Validates the MFA code entered by the user

    public boolean validateMfaCode(String inputCode, String storedCode) {

        return inputCode.equals(storedCode);

    }

    // This method simulates sending the verification code to the user via email/SMS

    public void sendVerificationCode(String email, String code) {

        // Implementation for sending the code (e.g., via email or SMS)

        System.out.println("Sending verification code " + code + " to " + email);

    }

    // Checks if the user is authenticated and handles MFA logic

    public boolean authenticateUserWithMfa(String email, String password, String inputCode) {

        UserDetails userDetails = userDetailsService.loadUserByUsername(email);

        if (userDetails != null && passwordEncoder.matches(password, userDetails.getPassword())) {

            // Generate and send verification code

            String verificationCode = generateVerificationCode();

            sendVerificationCode(email, verificationCode);

            // Simulate waiting for user to enter the code

            // In a real application, you would need to store the verification code temporarily

            // for comparison with the input code.

            // Here, we will assume the user entered the correct code for demonstration purposes.

            // This would typically involve a separate process to handle user input.

            return validateMfaCode(inputCode, verificationCode);

        }

        return false;

    }

}

Explanation of the MultiFactorAuth Class

  1. Class Annotations:
    • @Service: Marks this class as a Spring service, allowing it to be managed by Spring’s dependency injection.
  2. Dependencies:
    • UserDetailsService: A Spring Security interface to load user-specific data.
    • PasswordEncoder: Used to encode and verify passwords securely.
  3. Methods:
    • generateVerificationCode():
      • Generates a random 6-digit verification code for MFA using Java's Random class.
    • validateMfaCode(String inputCode, String storedCode):
      • Compares the input code provided by the user with the stored verification code. Returns true if they match; otherwise, returns false.
    • sendVerificationCode(String email, String code):
      • Simulates sending the verification code to the user. In a real application, this could involve sending an email or SMS.
      • For this example, it prints the code to the console.
    • authenticateUserWithMfa(String email, String password, String inputCode):
      • Authenticates the user using their email and password.
      • If authentication is successful, it generates and sends a verification code to the user.
      • Finally, it validates the MFA code entered by the user. This method simulates the MFA process, assuming that the correct code is entered.

Conclusion

The MultiFactorAuth class is an essential part of the security mechanism in your Online Banking System, implementing multi-factor authentication to enhance security during user login. You can expand this class by integrating real email/SMS services to send verification codes or by improving the flow to better handle user input for MFA. 

UserRepository.java

 This interface will handle database operations related to the User entity, leveraging Spring Data JPA to simplify data access.

package com.banking.repository;

import com.banking.model.User;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository

public interface UserRepository extends JpaRepository<User, Long> {

    // Method to find a user by their email address

    Optional<User> findByEmail(String email);

    // Method to check if a user exists by email

    boolean existsByEmail(String email);

}

Explanation of the UserRepository Interface

  1. Class Annotations:
    • @Repository: Indicates that the interface is a Spring Data repository, enabling exception translation for database-related operations.
  2. Extending JpaRepository:
    • The UserRepository interface extends JpaRepository<User, Long>, which provides various CRUD operations out of the box for the User entity.
      • User: The entity type that the repository will manage.
      • Long: The type of the entity's primary key.
  3. Custom Methods:
    • Optional<User> findByEmail(String email):
      • This method retrieves a User object based on the provided email address. It returns an Optional<User>, which allows you to handle cases where no user is found without throwing an exception.
    • boolean existsByEmail(String email):
      • This method checks if a user exists with the given email address. It returns a boolean value, which is useful for validations, such as during user registration.

Conclusion

The UserRepository interface simplifies the interaction with the database for user-related operations in your Online Banking System. By extending JpaRepository, you inherit various methods for managing user data, and you can easily add custom queries as needed.

AccountRepository.java 

This interface will handle database operations related to the Account entity, utilizing Spring Data JPA to streamline data access.

package com.banking.repository;

import com.banking.model.Account;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository

public interface AccountRepository extends JpaRepository<Account, Long> {

 // Method to find an account by its account number

    Optional<Account> findByAccountNumber(String accountNumber);

   // Method to find accounts by user ID

    List<Account> findByUserId(Long userId);

   // Method to check if an account exists by its account number

    boolean existsByAccountNumber(String accountNumber);

}

Explanation of the AccountRepository Interface

  1. Class Annotations:
    • @Repository: Indicates that the interface is a Spring Data repository, enabling exception translation for database-related operations.
  2. Extending JpaRepository:
    • The AccountRepository interface extends JpaRepository<Account, Long>, providing various CRUD operations for the Account entity.
      • Account: The entity type that the repository will manage.
      • Long: The type of the entity's primary key.
  3. Custom Methods:
    • Optional<Account> findByAccountNumber(String accountNumber):
      • This method retrieves an Account object based on the provided account number. It returns an Optional<Account>, which allows for handling cases where no account is found without throwing an exception.
    • List<Account> findByUserId(Long userId):
      • This method retrieves a list of accounts associated with a specific user ID. This is useful for displaying all accounts linked to a user.
    • boolean existsByAccountNumber(String accountNumber):
      • This method checks if an account exists with the given account number. It returns a boolean value, useful for validations, such as during account creation.

Conclusion

The AccountRepository interface simplifies the interaction with the database for account-related operations in your Online Banking System. By extending JpaRepository, you inherit various methods for managing account data, and you can easily add custom queries as needed. 

TransactionRepository.java

This interface will handle database operations related to the Transaction entity, utilizing Spring Data JPA to simplify data access.

package com.banking.repository;

import com.banking.model.Transaction;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface TransactionRepository extends JpaRepository<Transaction, Long> {

    // Method to find transactions by user ID

    List<Transaction> findByUserId(Long userId);

    // Method to find transactions by account ID

    List<Transaction> findByAccountId(Long accountId);

    // Method to find transactions by transaction type (e.g., Deposit, Withdraw)

    List<Transaction> findByTransactionType(String transactionType);

}

Explanation of the TransactionRepository Interface

  1. Class Annotations:
    • @Repository: Marks the interface as a Spring Data repository, enabling exception translation for database-related operations.
  2. Extending JpaRepository:
    • The TransactionRepository interface extends JpaRepository<Transaction, Long>, providing various CRUD operations for the Transaction entity.
      • Transaction: The entity type that the repository will manage.
      • Long: The type of the entity's primary key.
  3. Custom Methods:
    • List<Transaction> findByUserId(Long userId):
      • This method retrieves a list of transactions associated with a specific user ID. This is useful for displaying all transactions linked to a user.
    • List<Transaction> findByAccountId(Long accountId):
      • This method retrieves a list of transactions associated with a specific account ID. This allows you to view all transactions for a particular account.
    • List<Transaction> findByTransactionType(String transactionType):
      • This method retrieves a list of transactions based on their type (e.g., "Deposit", "Withdraw"). This is useful for filtering transactions by type for reporting or auditing purposes.

Conclusion

The TransactionRepository interface simplifies the interaction with the database for transaction-related operations in your Online Banking System. By extending JpaRepository, you inherit various methods for managing transaction data and can easily add custom queries as needed. 

UserService.java

 This service will handle the business logic related to user operations, including user registration, login, and retrieval of user details.package com.banking.service;

import com.banking.model.User;

import com.banking.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.Optional;

 

@Service

@Transactional

public class UserService {

    @Autowired

    private UserRepository userRepository;

    @Autowired

    private PasswordEncoder passwordEncoder;

    // Method to register a new user

    public User registerUser(User user) {

        // Encode the user's password before saving

        user.setPassword(passwordEncoder.encode(user.getPassword()));

        return userRepository.save(user);

    }

    // Method to find a user by email

    public Optional<User> findByEmail(String email) {

        return userRepository.findByEmail(email);

    }

    // Method to check if a user exists by email

    public boolean userExists(String email) {

        return userRepository.existsByEmail(email);

    }

    // Method to retrieve user by ID

    public Optional<User> findById(Long id) {

        return userRepository.findById(id);

    }

 

    // Method to update user details

    public User updateUser(User user) {

        // Ensure that the user exists before updating

        if (userRepository.existsById(user.getId())) {

            return userRepository.save(user);

        }

        return null; // Or throw an exception

    }

}

Explanation of the UserService Class

  1. Class Annotations:
    • @Service: Marks this class as a Spring service, making it eligible for component scanning and dependency injection.
    • @Transactional: Indicates that the methods in this class will execute within a transactional context, allowing for easier rollback on errors.
  2. Dependencies:
    • UserRepository: Injected to perform database operations related to the User entity.
    • PasswordEncoder: Used to encode and decode passwords securely.
  3. Methods:
    • User registerUser(User user):
      • This method registers a new user by encoding their password and saving the user to the database.
    • Optional<User> findByEmail(String email):
      • This method retrieves a user by their email address using the repository, returning an Optional<User>.
    • boolean userExists(String email):
      • This method checks if a user exists with the specified email address using the repository's existsByEmail method.
    • Optional<User> findById(Long id):
      • This method retrieves a user by their ID, returning an Optional<User>.
    • User updateUser(User user):
      • This method updates user details. It checks if the user exists in the database before saving. If the user does not exist, it returns null (you could also throw an exception for better error handling).

Conclusion

The UserService class encapsulates the business logic for user-related operations in your Online Banking System. It interacts with the UserRepository to perform CRUD operations and manages user registration and retrieval, ensuring proper password handling.

AccountService.java

This service will handle the business logic related to account operations, including account creation, retrieval, and management of account transactions.

package com.banking.service;

import com.banking.model.Account;

import com.banking.repository.AccountRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.List;

import java.util.Optional;

 @Service

@Transactional

public class AccountService {

 @Autowired

    private AccountRepository accountRepository;

     // Method to create a new account

    public Account createAccount(Account account) {

        return accountRepository.save(account);

    }

 // Method to find an account by its account number

    public Optional<Account> findByAccountNumber(String accountNumber) {

        return accountRepository.findByAccountNumber(accountNumber);

    }

     // Method to find accounts by user ID

    public List<Account> findByUserId(Long userId) {

        return accountRepository.findByUserId(userId);

    }

 // Method to update account details

    public Account updateAccount(Account account) {

        // Ensure that the account exists before updating

        if (accountRepository.existsByAccountNumber(account.getAccountNumber())) {

            return accountRepository.save(account);

        }

        return null; // Or throw an exception

    }

    // Method to delete an account by ID

    public void deleteAccount(Long id) {

        accountRepository.deleteById(id);

    }

}

Explanation of the AccountService Class

  1. Class Annotations:
    • @Service: Marks this class as a Spring service, making it eligible for component scanning and dependency injection.
    • @Transactional: Indicates that the methods in this class will execute within a transactional context, allowing for easier rollback on errors.
  2. Dependencies:
    • AccountRepository: Injected to perform database operations related to the Account entity.
  3. Methods:
    • Account createAccount(Account account):
      • This method creates a new account by saving it to the database through the accountRepository.
    • Optional<Account> findByAccountNumber(String accountNumber):
      • This method retrieves an account by its account number, returning an Optional<Account> to handle cases where the account may not exist.
    • List<Account> findByUserId(Long userId):
      • This method retrieves a list of accounts associated with a specific user ID.
    • Account updateAccount(Account account):
      • This method updates account details. It checks if the account exists before saving. If the account does not exist, it returns null (you could also throw an exception for better error handling).
    • void deleteAccount(Long id):
      • This method deletes an account from the database by its ID.

Conclusion

The AccountService class encapsulates the business logic for account-related operations in your Online Banking System. It interacts with the AccountRepository to perform CRUD operations, manage account retrieval, and handle account updates and deletions. 

TransactionService.java

This service will handle the business logic related to transaction operations, including transaction creation, retrieval, and management of transaction records.

package com.banking.service;

import com.banking.model.Transaction;

import com.banking.repository.TransactionRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

import java.util.List;

 @Service

@Transactional

public class TransactionService {

 @Autowired

    private TransactionRepository transactionRepository;

     // Method to create a new transaction

    public Transaction createTransaction(Transaction transaction) {

        return transactionRepository.save(transaction);

    }

 // Method to find transactions by user ID

    public List<Transaction> findByUserId(Long userId) {

        return transactionRepository.findByUserId(userId);

    }

    // Method to find transactions by account ID

    public List<Transaction> findByAccountId(Long accountId) {

        return transactionRepository.findByAccountId(accountId);

    }

    // Method to find transactions by transaction type

    public List<Transaction> findByTransactionType(String transactionType) {

        return transactionRepository.findByTransactionType(transactionType);

    }

     // Method to delete a transaction by ID

    public void deleteTransaction(Long id) {

        transactionRepository.deleteById(id);

    }

}

Explanation of the TransactionService Class

  1. Class Annotations:
    • @Service: Marks this class as a Spring service, making it eligible for component scanning and dependency injection.
    • @Transactional: Indicates that the methods in this class will execute within a transactional context, allowing for easier rollback on errors.
  2. Dependencies:
    • TransactionRepository: Injected to perform database operations related to the Transaction entity.
  3. Methods:
    • Transaction createTransaction(Transaction transaction):
      • This method creates a new transaction by saving it to the database through the transactionRepository.
    • List<Transaction> findByUserId(Long userId):
      • This method retrieves a list of transactions associated with a specific user ID.
    • List<Transaction> findByAccountId(Long accountId):
      • This method retrieves a list of transactions associated with a specific account ID.
    • List<Transaction> findByTransactionType(String transactionType):
      • This method retrieves a list of transactions based on their type (e.g., "Deposit", "Withdraw"). This is useful for filtering transactions by type.
    • void deleteTransaction(Long id):
      • This method deletes a transaction from the database by its ID.

Conclusion

The TransactionService class encapsulates the business logic for transaction-related operations in your Online Banking System. It interacts with the TransactionRepository to perform CRUD operations, manage transaction retrieval, and handle transaction deletions. 

OnlineBankingSystemApplication.java

This class serves as the entry point for your Spring Boot application and contains the main method to run the application.

package com.banking;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class OnlineBankingSystemApplication {

    public static void main(String[] args) {

        // Start the Spring Boot application

    SpringApplication.run(OnlineBankingSystemApplication.class, args);

    }

}

Explanation of the OnlineBankingSystemApplication Class

  1. Class Annotations:
    • @SpringBootApplication: This annotation serves as a combination of three annotations:
      • @Configuration: Indicates that the class can be used by the Spring IoC container as a source of bean definitions.
      • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on the classpath settings, other beans, and various property settings. It automatically configures the application based on the dependencies in the classpath.
      • @ComponentScan: Enables component scanning, allowing Spring to find and register beans (components, services, repositories) within the specified package and its sub-packages.
  2. Main Method:
    • The main method is the entry point for the Spring Boot application.
    • SpringApplication.run(...) starts the application and initializes the Spring context.

Conclusion

The OnlineBankingSystemApplication class is a critical component of your Spring Boot application, serving as the main entry point to launch the application. With the @SpringBootApplication annotation, it automatically configures various aspects of your application, making it easier to set up and run. 

OnlineBankingSystemApplicationTests.java

This class is used to write unit tests for your Spring Boot application to ensure that the application components behave as expected.

package com.banking;

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest

class OnlineBankingSystemApplicationTests {

   @Test

    void contextLoads() {

        // This test verifies that the Spring application context loads successfully.

    }

}

Explanation of the OnlineBankingSystemApplicationTests Class

  1. Class Annotations:
    • @SpringBootTest: This annotation indicates that the test class is a Spring Boot test. It loads the application context and enables you to test the application as a whole, making sure all components are wired together correctly.
  2. Test Method:
    • void contextLoads():
      • This test method checks if the Spring application context loads successfully. If the application context fails to load, the test will fail, indicating that there is an issue with the configuration or setup of the application.

Conclusion

The OnlineBankingSystemApplicationTests class is a simple yet essential part of your testing strategy for the Online Banking System. By verifying that the application context loads without issues, you can ensure that your application components are configured correctly. As you develop your application further, you can add more specific test cases to verify the functionality of various components, such as services and controllers.

pom.xml

This file manages the dependencies, build configuration, and plugins needed for your project. Make sure to adjust the version numbers as per your requirements and add or remove dependencies based on your specific project needs.

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

 

    <groupId>com.banking</groupId>

    <artifactId>OnlineBankingSystem</artifactId>

    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>

 

    <name>Online Banking System</name>

    <description>A simple online banking system using Spring Boot</description>

 

    <properties>

        <java.version>17</java.version>

        <spring.boot.version>2.7.10</spring.boot.version>

    </properties>

 

    <dependencies>

        <!-- Spring Boot Starter Web for building web applications -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

 

        <!-- Spring Boot Starter Data JPA for working with databases -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

 

        <!-- MySQL Driver for database connection -->

        <dependency>

            <groupId>mysql</groupId>

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

            <scope>runtime</scope>

        </dependency>

 

        <!-- Spring Security for authentication and authorization -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-security</artifactId>

        </dependency>

 

        <!-- Spring Boot Starter Test for testing your application -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

 

        <!-- Optional: Lombok for reducing boilerplate code (getters/setters) -->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <scope>provided</scope>

        </dependency>

 

        <!-- Optional: Spring Boot DevTools for easier development -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

            <optional>true</optional>

        </dependency>

 

        <!-- Optional: Validation API for validating input -->

        <dependency>

            <groupId>javax.validation</groupId>

            <artifactId>validation-api</artifactId>

            <version>2.0.1.Final</version>

        </dependency>

    </dependencies>

 

    <build>

        <plugins>

            <!-- Spring Boot Maven Plugin for building executable jars -->

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

 

            <!-- Maven Compiler Plugin to set the Java version -->

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <version>3.8.1</version>

                <configuration>

                    <source>${java.version}</source>

                    <target>${java.version}</target>

                </configuration>

            </plugin>

        </plugins>

    </build>

</project>

Explanation of the pom.xml

  1. Project Information:
    • Specifies the group ID, artifact ID, version, packaging type, name, and description of the project.
  2. Properties:
    • Sets properties for the Java version and Spring Boot version to manage versions easily.
  3. Dependencies:
    • Spring Boot Starter Web: For building web applications (including RESTful services).
    • Spring Boot Starter Data JPA: For accessing and managing relational databases using Spring Data JPA.
    • MySQL Connector: Required for connecting to a MySQL database.
    • Spring Boot Starter Security: For implementing authentication and authorization features.
    • Spring Boot Starter Test: For testing purposes.
    • Lombok: Optional dependency to reduce boilerplate code in Java classes.
    • Spring Boot DevTools: Optional dependency for improved development experience.
    • Validation API: Optional dependency for validating user inputs.
  4. Build Plugins:
    • Spring Boot Maven Plugin: For building executable JAR files.
    • Maven Compiler Plugin: Specifies the Java version for compiling the project.

Conclusion

This pom.xml file provides a solid foundation for your Online Banking System project, including necessary dependencies and build configurations.

README.md

This file provides an overview of the project, installation instructions, usage guidelines, and other relevant information.

# Online Banking System

A simple online banking system built using Spring Boot, Java, and MySQL. This application allows users to manage accounts, perform transactions, and access customer support with secure login and multi-factor authentication.

 ## Features

 - User Registration and Authentication

- Account Management

- Fund Transfers

- Transaction History

- Multi-Factor Authentication

- Secure User Interface

 ## Technologies Used

 - Java 17

- Spring Boot 2.7.10

- Spring Data JPA

- MySQL

- Spring Security

- Maven

## Prerequisites

 - JDK 17 or higher

- MySQL Server

- Maven

- IDE (e.g., IntelliJ IDEA, Eclipse)

 

## Installation

 1. **Clone the repository:**

    ```bash

   git clone https://github.com/yourusername/OnlineBankingSystem.git

   cd OnlineBankingSystem

  1. Create a MySQL database:

CREATE DATABASE online_banking_system;

  1. Configure MySQL connection:

Open src/main/resources/application.properties and update the following properties with your database credentials:

spring.datasource.url=jdbc:mysql://localhost:3306/online_banking_system

spring.datasource.username=your_mysql_username

spring.datasource.password=your_mysql_password

spring.jpa.hibernate.ddl-auto=update

  1. Build the application:

Run the following command to build the project:

mvn clean install

  1. Run the application:

You can run the application using your IDE or by executing the following command:

mvn spring-boot:run

The application will start on http://localhost:8080.

Usage

  1. Register a new user:
    • Send a POST request to /api/auth/register with user details (username, password, email).
  2. Login:
    • Send a POST request to /api/auth/login with credentials (username, password) to receive a JWT token.
  3. Account Management:
    • Create, retrieve, update, and delete accounts using appropriate endpoints (e.g., /api/accounts).
  4. Transactions:
    • Perform transactions like fund transfers and view transaction history through respective endpoints.

Testing

You can run unit tests using Maven:

mvn test

Contributing

Contributions are welcome! Please fork the repository and submit a pull request.

Contact

For any questions or feedback, please contact [lopalopa2007@gmail.com].

### Explanation of the `README.md`

1. **Project Title and Description**: A brief overview of the project and its purpose.

2. **Features**: A list of key features available in the application.

3. **Technologies Used**: An overview of the technologies and frameworks employed in the project.

4. **Prerequisites**: A list of software requirements needed to run the project.

5. **Installation**: Step-by-step instructions for cloning the repository, creating a MySQL database, configuring database properties, building, and running the application.

6. **Usage**: Information on how to register users, log in, manage accounts, and perform transactions.

7. **Testing**: Instructions for running unit tests.

8. **Contributing**: Guidelines for contributing to the project.

9. **License**: Information about the project's licensing.

10. **Contact**: Contact information for questions or feedback.

 ### Conclusion

This `README.md` file provides a comprehensive overview of your Online Banking System project, making it easy for others to understand, set up, and use the application. 

Post a Comment

0Comments

Post a Comment (0)