Home Blog Page 81

Installing MongoDB Locally and via Atlas (Cloud)

0
mongodb course
mongodb course

Introduction

In this module, we’ll guide you through the process of setting up MongoDB both locally on your machine and in the cloud via MongoDB Atlas. MongoDB Atlas is a fully managed cloud service provided by MongoDB, making it easier to set up, scale, and manage your databases without the complexity of manual configuration.

By the end of this module, you will:

  • Understand the steps involved in installing MongoDB locally.
  • Learn how to create and configure a MongoDB cluster using MongoDB Atlas.

1. Installing MongoDB Locally

Step 1: Download MongoDB

  1. Visit the official MongoDB website:
    MongoDB Download Center
  2. Select your operating system (Windows, macOS, or Linux).
  3. Choose the version of MongoDB you want to install (select the latest stable version).
  4. Click on the Download button. The installer will be downloaded to your machine.

Step 2: Installing MongoDB

On Windows:
  1. Once the installer is downloaded, double-click to launch it.
  2. During the installation process, select Complete for the installation type.
  3. Make sure the option “Install MongoDB as a Service” is selected. This will allow MongoDB to run automatically as a background service after installation.
  4. Choose the installation directory (you can use the default location).
  5. After installation, click Finish.
On macOS:
  1. Homebrew is the easiest way to install MongoDB on macOS. If you don’t have Homebrew installed, you can install it by running the following command in the terminal: /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. To install MongoDB using Homebrew, run the following command in your terminal: brew tap mongodb/brew brew install [email protected]
  3. After installation, start MongoDB using the following command: brew services start mongodb/brew/mongodb-community
On Linux:
  1. Open your terminal and update your package index: sudo apt-get update
  2. Install MongoDB: sudo apt-get install -y mongodb
  3. Start MongoDB using the following command: sudo systemctl start mongodb
  4. To ensure MongoDB starts on boot, enable it: sudo systemctl enable mongodb

Step 3: Verify the Installation

  1. Open a command prompt (Windows) or terminal (macOS/Linux).
  2. Type the following command to enter the Mongo shell: mongo
  3. If MongoDB is successfully installed and running, you should see the Mongo shell prompt, which looks like this: >
  4. To check the current MongoDB version, run: db.version()

2. Installing MongoDB via Atlas (Cloud)

Step 1: Create a MongoDB Atlas Account

  1. Visit MongoDB Atlas.
  2. Click Get Started Free to create an account. You can sign up using your Google account or an email address.
  3. Once your account is created, log in to the MongoDB Atlas dashboard.

Step 2: Create a Cluster

  1. After logging in, click on the “Build a Cluster” button.
  2. Select the Cloud Provider and Region closest to your application’s location (e.g., AWS, Google Cloud, or Azure).
  3. Choose the Cluster Tier. MongoDB Atlas offers a free-tier cluster (M0), which is ideal for development and testing purposes.
  4. Click Create Cluster. This may take a few minutes.

Step 3: Set Up Network Access

  1. After your cluster is created, navigate to the Network Access tab in the MongoDB Atlas dashboard.
  2. Under the IP Whitelist section, click Add IP Address.
  3. Add your current IP address (you can use 0.0.0.0/0 to allow all IP addresses, but this is not recommended for production environments).
  4. Click Confirm to allow network access.

Step 4: Create a Database User

  1. Go to the Database Access tab in the MongoDB Atlas dashboard.
  2. Click Add New Database User.
  3. Choose a username and password for your database user.
  4. Assign Database User Privileges as necessary (for general use, the default privileges are usually sufficient).
  5. Click Add User.

Step 5: Connect to Your Cluster

  1. Go to the Clusters tab in the MongoDB Atlas dashboard.
  2. Click Connect for your newly created cluster.
  3. Select Connect your application.
  4. Copy the connection string provided by MongoDB Atlas.
    • The connection string will look like this: mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority
  5. Replace <username> and <password> with your MongoDB Atlas database user credentials.
  6. You can now use this connection string to connect to MongoDB from your application (Node.js, Java, etc.) or MongoDB shell.

3. Using MongoDB Atlas with Mongo Shell

If you want to interact with your MongoDB Atlas database from the command line, you can use the Mongo shell.

  1. First, ensure that the Mongo shell is installed on your machine. If not, you can download it from the MongoDB Downloads page.
  2. Once installed, run the following command to connect to your MongoDB Atlas cluster: mongo "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority"
  3. After connecting, you can start running MongoDB commands just like you would with a local installation.

Conclusion

In this module, we’ve covered the steps to install MongoDB both locally and in the cloud using MongoDB Atlas. Local installation provides the flexibility of running MongoDB on your own machine, while MongoDB Atlas offers the advantages of a fully-managed, scalable cloud-based database solution.

What is MongoDB? NoSQL vs SQL Overview

0
mongodb course
mongodb course

Introduction

In this module, we’ll dive into the basics of MongoDB and explore its features, strengths, and why it’s such a powerful tool for modern web development. Additionally, we’ll compare NoSQL and SQL databases to understand when and why you might choose MongoDB over a traditional relational database.


What is MongoDB?

MongoDB is an open-source, NoSQL (Not Only SQL) database designed for scalability, performance, and ease of use. It stores data in a document-based format, typically in JSON-like structures called BSON (Binary JSON). Unlike traditional relational databases that use tables and rows, MongoDB uses collections and documents.

  • Collections: Equivalent to tables in SQL databases, collections are groups of documents.
  • Documents: Equivalent to rows in SQL databases, but in MongoDB, documents are flexible and can contain any number of fields with varying data types.

MongoDB is designed to handle unstructured data and large volumes of data that don’t fit easily into the rigid structure of relational databases. This flexibility makes it a popular choice for developers working with modern, distributed, and real-time applications.


Key Features of MongoDB

  1. Schema-less: MongoDB is schema-less, meaning that documents within a collection can have different structures. This makes it ideal for storing unstructured or semi-structured data, such as JSON data from web services, social media posts, or sensor data.
  2. Scalability: MongoDB is designed to scale horizontally by using sharding, which distributes data across multiple servers. This makes it suitable for applications with high write loads and large datasets.
  3. Replication: MongoDB supports replication, ensuring data availability and redundancy. Data is replicated across multiple servers (nodes), which provides high availability and fault tolerance.
  4. Flexible Data Model: MongoDB uses a document-oriented model with a JSON-like format, making it more intuitive to store and manipulate data, especially when dealing with hierarchical or nested data.
  5. Indexing: MongoDB supports powerful indexing, including single field, compound, and geospatial indexes, which significantly improve query performance.
  6. Aggregation Framework: MongoDB offers an aggregation framework for performing operations like filtering, sorting, grouping, and transforming data. This allows for more complex queries and computations within the database.

NoSQL vs SQL Databases

1. Structure of Data

  • SQL: Structured data is stored in tables with predefined schemas. Each row in a table represents an entity, and each column represents an attribute of the entity. Data must conform to the schema, and any change in the schema requires altering the database structure (such as adding columns).
  • NoSQL: In NoSQL databases like MongoDB, data is stored in collections of documents (often in a JSON or BSON format). This schema-less structure allows for flexibility, as documents within a collection can have different fields.

2. Data Integrity and ACID Compliance

  • SQL: SQL databases typically follow ACID (Atomicity, Consistency, Isolation, Durability) properties, ensuring strong consistency and data integrity. SQL databases are a good choice when your application needs strict data integrity, such as in banking systems.
  • NoSQL: NoSQL databases, including MongoDB, follow BASE (Basically Available, Soft state, Eventually consistent) instead of ACID. This means that while MongoDB ensures availability and fault tolerance, it may not always guarantee immediate consistency across nodes, especially in a distributed system. However, MongoDB offers eventual consistency, which means it eventually reaches a consistent state across all replicas.

3. Scaling

  • SQL: Traditional SQL databases are typically scaled vertically (i.e., increasing the power of a single server). While they can be horizontally scaled (via sharding), it is often complex and requires specialized tools and techniques.
  • NoSQL: NoSQL databases like MongoDB are designed to be scaled horizontally. They handle large amounts of data and high traffic loads by distributing data across multiple servers in a process called sharding.

4. Querying

  • SQL: SQL databases use the Structured Query Language (SQL) for querying data. SQL queries are powerful for complex joins, aggregations, and other relational operations. However, SQL queries can become complicated when working with nested or unstructured data.
  • NoSQL: NoSQL databases use different query mechanisms. In MongoDB, data is queried using BSON format and MongoDB Query Language (MQL). MongoDB’s aggregation framework provides powerful querying, filtering, and data transformation capabilities, but without the need for complex joins.

5. Use Cases

  • SQL: Best suited for applications requiring complex transactions, data integrity, and relationships between entities. Examples include:
    • Banking applications
    • Enterprise resource planning (ERP) systems
    • Customer relationship management (CRM) systems
  • NoSQL (MongoDB): Best suited for applications that need to handle large volumes of unstructured data or require fast scaling and flexibility. Examples include:
    • Real-time applications (e.g., social media, messaging)
    • Big data applications
    • Content management systems (CMS)
    • IoT (Internet of Things) applications

When to Use MongoDB?

You might consider using MongoDB if:

  • Your data model is likely to change over time and needs to be flexible.
  • You are working with large-scale, distributed applications.
  • You need fast read and write performance.
  • Your application will work with unstructured data (e.g., JSON, sensor data).
  • You want to take advantage of horizontal scaling to handle high traffic.

Conclusion

MongoDB is a powerful and flexible NoSQL database that shines in scenarios where scalability, flexibility, and performance are critical. It differs from traditional SQL databases by offering a schema-less design and providing horizontal scalability and high availability. Understanding the differences between NoSQL and SQL databases helps developers choose the right tool for the job based on their specific use cases and requirements.

Interview Series: Top Java + Spring Boot Interview Questions & Answers

0
java spring boot course
java spring boot course

Here’s a curated interview series on Java and Spring Boot. The following list includes the top interview questions along with comprehensive answers that can help candidates prepare for technical interviews.


1. What is the difference between JDK, JRE, and JVM?

Answer:

  • JDK (Java Development Kit): It is a software development kit used to develop Java applications. It includes the JRE and development tools such as compilers and debuggers.
  • JRE (Java Runtime Environment): It is a runtime environment that allows you to run Java applications. It includes the JVM and libraries necessary to run applications but doesn’t provide the tools to develop them.
  • JVM (Java Virtual Machine): It is the engine that runs Java bytecode. It is platform-independent and helps Java achieve its “write once, run anywhere” capability.

2. What is the concept of Object-Oriented Programming in Java?

Answer: Object-Oriented Programming (OOP) in Java is a programming paradigm based on the concept of “objects” and “classes”. The key principles of OOP are:

  1. Encapsulation: Bundling the data (attributes) and methods (functions) that operate on the data into a single unit known as a class. It helps in data hiding and access control.
  2. Abstraction: Hiding the complex implementation details and showing only the essential features. This is achieved using abstract classes and interfaces.
  3. Inheritance: Mechanism to define a new class based on an existing class, inheriting its properties and behaviors, thus promoting code reuse.
  4. Polymorphism: The ability of an object to take on multiple forms. It includes method overloading (compile-time polymorphism) and method overriding (runtime polymorphism).

3. What are the different types of collections in Java?

Answer: Java collections can be broadly classified into three types:

  1. List: An ordered collection that allows duplicate elements. Example: ArrayList, LinkedList.
  2. Set: A collection that doesn’t allow duplicate elements. Example: HashSet, LinkedHashSet.
  3. Map: A collection that stores key-value pairs, where each key is unique. Example: HashMap, TreeMap.

Additional interfaces and classes in collections include Queue, Deque, and Stack.


4. What is the difference between == and .equals() in Java?

Answer:

  • ==: It is a reference comparison operator. It checks if two object references point to the same memory location.
  • .equals(): It is a method provided by the Object class. It checks the actual content of two objects to see if they are logically equivalent. It’s commonly overridden in custom classes to define a content-based equality check.

5. Explain Spring Boot’s auto-configuration feature.

Answer: Spring Boot’s auto-configuration feature automatically configures Spring application context based on the libraries in the classpath and the properties defined in the application. It simplifies the configuration process by guessing the required configurations based on the environment and dependencies.

For example, if Spring Boot detects a H2 database in the classpath, it will automatically configure a data source, JDBC connection, etc., without the need for explicit configuration.


6. What is Dependency Injection (DI) in Spring?

Answer: Dependency Injection is a design pattern where an object’s dependencies (services, repositories, etc.) are provided to it from the outside rather than the object creating the dependencies itself. This is a core concept in Spring, and it helps with:

  • Loose Coupling: Objects don’t need to know how to create their dependencies, making the system more flexible.
  • Easier Testing: Dependencies can be injected using mock objects or stubs during testing.

Spring supports three types of dependency injection:

  • Constructor Injection
  • Setter Injection
  • Field Injection

7. What are Spring Boot Starter POMs?

Answer: Spring Boot Starter POMs are a set of pre-configured dependencies that help developers quickly set up common functionalities. These “starters” provide a simple way to include commonly used libraries, configurations, and tools in the Spring Boot project.

For example:

  • spring-boot-starter-web: Includes dependencies for building web applications (Spring MVC, Tomcat, etc.).
  • spring-boot-starter-data-jpa: Includes dependencies for working with databases using Spring Data JPA.
  • spring-boot-starter-test: Includes testing libraries like JUnit, Mockito, and Spring Test.

8. What is the role of @SpringBootApplication annotation?

Answer: The @SpringBootApplication annotation is a convenience annotation in Spring Boot that combines several other annotations:

  1. @Configuration: Marks the class as a source of bean definitions for the application context.
  2. @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
  3. @ComponentScan: Tells Spring to scan the current package and its sub-packages for components.

This annotation is typically placed on the main class to set up the Spring Boot application context and start the application.


9. What is the difference between @Component, @Service, @Repository, and @Controller annotations?

Answer: These annotations are all part of Spring’s component scanning and define the role of the beans in the application.

  1. @Component: A general-purpose stereotype annotation used to define a Spring bean.
  2. @Service: A specialization of @Component, used to define service beans (business logic).
  3. @Repository: A specialization of @Component, used to define DAO beans (data access objects). It also enables exception translation (converts database-related exceptions to Spring’s DataAccessException).
  4. @Controller: A specialization of @Component, used to define Spring MVC controllers, handling HTTP requests.

10. What is Spring AOP and how is it used?

Answer: Spring AOP (Aspect-Oriented Programming) is a programming paradigm that allows you to separate cross-cutting concerns (such as logging, transaction management, security, etc.) from the core business logic. This separation allows for cleaner code and better maintainability.

Key concepts in Spring AOP:

  • Aspect: A module that encapsulates a concern (e.g., logging or transaction management).
  • Advice: The action taken at a specific point in the program (before, after, or around method execution).
  • Pointcut: A predicate that defines where the advice should be applied (e.g., methods with a certain annotation).
  • Joinpoint: A point during the execution of the program (e.g., method execution) where the advice can be applied.

Spring AOP is typically used for declarative transaction management and logging.


11. Explain the lifecycle of a Spring Bean.

Answer: The lifecycle of a Spring bean can be broken down into the following steps:

  1. Instantiation: Spring creates the bean using the default or specified constructor.
  2. Dependency Injection: Spring injects dependencies into the bean using DI (via constructor, setter, or field).
  3. Initialization: Spring calls any custom initialization methods, such as those defined with the @PostConstruct annotation or InitializingBean interface.
  4. Usage: The bean is ready for use in the application.
  5. Destruction: If the bean is a singleton, it is destroyed when the context is closed. Spring calls any custom destroy methods defined with @PreDestroy or DisposableBean.

12. What is the difference between @RequestMapping and @GetMapping in Spring MVC?

Answer: Both @RequestMapping and @GetMapping are used to handle HTTP requests in Spring MVC, but they have different purposes:

  • @RequestMapping: It is a more general annotation used to map HTTP requests to handler methods. It supports all HTTP methods (GET, POST, PUT, DELETE, etc.). You can specify the request type using the method attribute. @RequestMapping(value = "/home", method = RequestMethod.GET) public String home() { return "home"; }
  • @GetMapping: It is a shortcut for @RequestMapping(method = RequestMethod.GET). It is specifically used for HTTP GET requests. @GetMapping("/home") public String home() { return "home"; }

13. What is the use of @Transactional annotation in Spring?

Answer: The @Transactional annotation in Spring is used to manage transactions. It ensures that all operations within a method are part of a single transaction. If any operation fails, the transaction is rolled back, and all changes are reverted. It can be applied at the method or class level.


These are just a few examples, but there are many more advanced questions and answers that can be discussed based on the experience level and the specific technologies in use.

Capstone Project: RESTful CRUD API with Spring Boot + JWT + MySQL

0
java spring boot course
java spring boot course

Table of Contents

  1. Introduction
  2. Project Setup
    • Setting up Spring Boot Application
    • Adding Dependencies
  3. Database Setup (MySQL)
    • Setting Up MySQL Database
    • Configuring MySQL Connection in Spring Boot
  4. Creating the User Model & Repository
  5. JWT Authentication
    • Creating JWT Utility Class
    • JWT Filter
    • Configuring Security Configuration
  6. User Registration and Login
    • Registration API
    • Login API
  7. Implementing CRUD Operations
    • Create, Read, Update, Delete Operations
  8. Exception Handling
  9. Testing the API
  10. Conclusion

1. Introduction

In this project, you will build a simple but powerful RESTful CRUD API using Spring Boot, JWT (JSON Web Token) for secure authentication, and MySQL as the relational database. This project will help you understand how to create secure, efficient, and scalable web services. By the end of the project, you will have a complete Spring Boot application with JWT authentication and basic CRUD functionality.


2. Project Setup

Setting up Spring Boot Application

First, create a new Spring Boot project using your preferred IDE (e.g., IntelliJ IDEA or Spring Tool Suite). You can also use Spring Initializr to generate a base project.

  • Group: com.example
  • Artifact: jwtcrudapi
  • Dependencies: Spring Web, Spring Data JPA, Spring Security, MySQL Driver, Lombok (optional), JWT (for token-based authentication)

pom.xml (Maven) Configuration Example:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>

Adding Dependencies

Ensure the necessary dependencies are added in the pom.xml or build.gradle. The required dependencies are:

  • Spring Boot Web: For building RESTful APIs.
  • Spring Data JPA: For ORM and database interaction.
  • Spring Security: For securing the application using JWT.
  • JWT: For generating and validating JSON Web Tokens.
  • MySQL: For the database connection.

3. Database Setup (MySQL)

Setting Up MySQL Database

You need a MySQL database to store user data. Here’s how to set it up:

  1. Install MySQL on your system or use a managed MySQL service.
  2. Create a Database: CREATE DATABASE jwtcrudapi;
  3. Create a User Table: CREATE TABLE users ( id BIGINT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) UNIQUE NOT NULL, password VARCHAR(255) NOT NULL, role VARCHAR(50) NOT NULL );

Configuring MySQL Connection in Spring Boot

In the application.properties or application.yml, configure the database connection settings:

spring.datasource.url=jdbc:mysql://localhost:3306/jwtcrudapi
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

4. Creating the User Model & Repository

Create the User entity to map to the users table and the corresponding JPA repository.

User Entity (User.java)

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
private String username;

private String password;

private String role; // e.g., "ROLE_USER"

// Getters and Setters
}

User Repository (UserRepository.java)

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}

5. JWT Authentication

In this section, we will create the necessary classes to handle JWT-based authentication.

JWT Utility Class (JwtUtils.java)

This utility class will handle JWT creation and validation.

@Component
public class JwtUtils {

private String jwtSecret = "secretKey"; // This should be in properties

public String generateJwtToken(Authentication authentication) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
return Jwts.builder()
.setSubject(userPrincipal.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + 86400000)) // 1 day expiry
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}

public String getUsernameFromJwtToken(String token) {
return Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody()
.getSubject();
}

public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (JwtException e) {
return false;
}
}
}

JWT Filter (JwtAuthenticationFilter.java)

This filter will intercept each request to validate the JWT token.

public class JwtAuthenticationFilter extends OncePerRequestFilter {

private JwtUtils jwtUtils;

public JwtAuthenticationFilter(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUsernameFromJwtToken(jwt);
// Set Authentication for Security Context
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
}

Security Configuration (WebSecurityConfig.java)

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private JwtUtils jwtUtils;

@Autowired
public WebSecurityConfig(JwtUtils jwtUtils) {
this.jwtUtils = jwtUtils;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JwtAuthenticationFilter(jwtUtils), UsernamePasswordAuthenticationFilter.class);
}
}

6. User Registration and Login

Registration API (AuthController.java)

@RestController
@RequestMapping("/auth")
public class AuthController {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtUtils jwtUtils;

@Autowired
private UserRepository userRepository;

@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody User user) {
// Validate user data, save to DB
userRepository.save(user);
return ResponseEntity.ok("User registered successfully");
}

@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
// Authenticate user and generate JWT token
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
String jwt = jwtUtils.generateJwtToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt));
}
}

7. Implementing CRUD Operations

Now, you can implement the CRUD operations. For simplicity, let’s create a Product resource that the user can interact with.

Product Model (Product.java)

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Double price;

// Getters and Setters
}

Product Repository (ProductRepository.java)

public interface ProductRepository extends JpaRepository<Product, Long> {
}

Product Controller (ProductController.java)

@RestController
@RequestMapping("/products")
public class ProductController {

@Autowired
private ProductRepository productRepository;

@GetMapping
public List<Product> getAllProducts() {
return productRepository.findAll();
}

@PostMapping
public Product createProduct(@RequestBody Product product) {
return productRepository.save(product);
}

@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
product.setName(productDetails.getName());
product.setPrice(productDetails.getPrice());
productRepository.save(product);
return ResponseEntity.ok(product);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product not found"));
productRepository.delete(product);
return ResponseEntity.noContent().build();
}
}

8. Exception Handling

Add a centralized exception handler using @ControllerAdvice to handle errors globally.

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFound(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}

9. Testing the API

You can test the API using tools like Postman or Swagger. For instance:

  • Register User: POST /auth/register
  • Login User: POST /auth/login
  • CRUD Operations: GET /products, POST /products, PUT /products/{id}, DELETE /products/{id}

10. Conclusion

This project demonstrates how to build a secure RESTful API with Spring Boot, JWT for authentication, and MySQL for data storage. By using JWT, we ensure stateless and secure authentication for the API. This can be the foundation for more advanced applications that require secure user authentication and CRUD operations.

Mini Projects: Banking App, Todo API, File Uploader, Blog Backend

0
java spring boot course
java spring boot course

Here’s a breakdown of the mini projects that can be done using Spring Boot, covering a variety of use cases to help you practice and gain proficiency:


1. Banking App

Project Overview: This project involves creating a basic banking system where users can create accounts, view balances, make deposits and withdrawals, and transfer money between accounts.

Key Features:

  • User registration and authentication using JWT.
  • Account creation with user details (name, email, etc.).
  • Balance inquiry and account details view.
  • Transfer money between accounts.
  • Deposit and withdraw funds from an account.
  • Transaction history for each account.

Key Technologies:

  • Spring Boot: For the backend.
  • Spring Security: For user authentication.
  • MySQL/PostgreSQL: To store user accounts and transaction details.
  • JWT: For stateless authentication.

Steps:

  1. Set up Spring Boot application with Spring Data JPA and Spring Security.
  2. Create User and Account models.
  3. Implement Deposit, Withdrawal, Transfer, and Balance Check services.
  4. Implement Transaction history to track deposits, withdrawals, and transfers.
  5. Secure endpoints with JWT authentication.

2. Todo API

Project Overview: This is a simple To-Do List API where users can register, create tasks, update task status, delete tasks, and view their tasks.

Key Features:

  • User registration and authentication with JWT.
  • CRUD operations for tasks (create, read, update, delete).
  • Mark tasks as completed or pending.
  • Pagination and sorting for tasks.
  • Task priority levels (low, medium, high).

Key Technologies:

  • Spring Boot: For the backend.
  • Spring Security: For user authentication.
  • Spring Data JPA: To store tasks in a database.
  • MySQL/PostgreSQL: For database management.

Steps:

  1. Set up a Spring Boot project with JWT authentication and Spring Data JPA.
  2. Create User and Task models.
  3. Implement CRUD operations for tasks.
  4. Implement sorting and pagination for tasks.
  5. Secure the API with JWT authentication.

3. File Uploader

Project Overview: This project involves building an application that allows users to upload files (images, documents, etc.) to the server and manage them.

Key Features:

  • User authentication and authorization using JWT.
  • Support for uploading multiple file types (images, PDFs, etc.).
  • Store file metadata (name, size, type).
  • Ability to view and download uploaded files.
  • Ability to delete uploaded files.

Key Technologies:

  • Spring Boot: For the backend.
  • Spring Security: For JWT-based authentication.
  • Spring Web: For file handling.
  • MySQL/PostgreSQL: To store file metadata.

Steps:

  1. Set up a Spring Boot application with JWT authentication.
  2. Create endpoints to handle file uploads and store the file metadata in the database.
  3. Implement functionality for file viewing and downloading.
  4. Secure API endpoints with JWT.
  5. Add validation for file types and size limits.

4. Blog Backend

Project Overview: This project is a simple backend for a blog where users can register, create blog posts, and comment on posts. The system should allow users to like and dislike posts.

Key Features:

  • User authentication and JWT-based session management.
  • CRUD operations for blog posts.
  • Commenting system on each blog post.
  • Like and dislike posts functionality.
  • Pagination and sorting of posts.

Key Technologies:

  • Spring Boot: For the backend.
  • Spring Security: For authentication using JWT.
  • Spring Data JPA: For data persistence (blog posts, comments, etc.).
  • MySQL/PostgreSQL: For storing data.

Steps:

  1. Set up a Spring Boot application with JWT authentication.
  2. Create models for User, Post, and Comment.
  3. Implement CRUD functionality for Posts and Comments.
  4. Implement the like/dislike functionality.
  5. Implement pagination and sorting for blog posts.
  6. Secure all the API endpoints with JWT authentication.

General Steps for All Projects:

  1. Set up Spring Boot Project:
    • Use Spring Initializr to generate the base Spring Boot project.
    • Add dependencies like Spring Web, Spring Data JPA, Spring Security, JWT (for authentication), MySQL/PostgreSQL, and Lombok if required.
  2. Create Models:
    • Define entities for your database, such as User, Post, Task, etc.
  3. Create Repositories:
    • Use Spring Data JPA repositories to interact with the database.
  4. Service Layer:
    • Implement business logic (CRUD operations, authentication, etc.) in the Service classes.
  5. Controller Layer:
    • Create REST controllers to expose the APIs and map them to the service layer.
  6. JWT Authentication:
    • Implement JWT authentication for security.
  7. Test the APIs:
    • Use tools like Postman or Swagger to test your APIs.

These mini projects provide hands-on experience with essential Spring Boot concepts and demonstrate the ability to build real-world applications. By completing them, you’ll gain a deeper understanding of working with databases, authentication, and building RESTful APIs with Spring Boot.