Spring Boot and MySQL are a powerful combination for building modern, scalable, and maintainable web applications. This tutorial will guide you through creating a Spring Boot application with CRUD (Create, Read, Update, Delete) operations and authentication using Spring Security and MySQL.
Before starting, ensure you have the following:
- Java 8 or higher installed.
- Maven for dependency management.
- MySQL installed and running.
- An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.
- Basic knowledge of Java and Spring Boot.
Step 1: Set Up the Project
1.1 Create a Spring Boot Project
Go to Spring Initializr.
Select the following options:
- Project: Maven
- Language: Java
- Spring Boot: 3.0.0+
Add dependencies:
- Spring Web
- Spring Data JPA
- MySQL Driver
- Spring Security
- Spring Boot DevTools
Click Generate to download the project.
Extract and open the project in your IDE.
Step 2: Configure MySQL Database
2.1 Create a Database
Open MySQL Workbench or your preferred database tool.
Run the following SQL command to create a database:
CREATE DATABASE spring_crud;
2.2 Configure application.properties
Open the src/main/resources/application.properties file and add the following:
spring.datasource.url=jdbc:mysql://localhost:3306/spring_crud
spring.datasource.username=your_mysql_username
spring.datasource.password=your_mysql_password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
Step 3: Create the User Entity and Repository
3.1 Define the User Entity
Create a User class in the model package:
package com.example.demo.model;
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String role;
// Getters and setters
}
3.2 Create the User Repository
Create a UserRepository interface in the repository package:
package com.example.demo.repository;
import com.example.demo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
Step 4: Set Up Spring Security
4.1 Configure Security
Create a SecurityConfig class in the config package:
package com.example.demo.config;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests()
.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
}
4.2 Authentication Service
Create an AuthenticationService class in the service package:
package com.example.demo.service;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
public User registerUser(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRole("USER");
return userRepository.save(user);
}
}
Step 5: Create RESTful APIs
5.1 Authentication Controller
Create an AuthController class in the controller package:
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationService authService;
@PostMapping("/register")
public String register(@RequestBody User user) {
authService.registerUser(user);
return "User registered successfully!";
}
}
5.2 CRUD Operations Controller
Create a UserController class in the controller package:
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public Optional<User> getUserById(@PathVariable Long id) {
return userRepository.findById(id);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = userRepository.findById(id).orElseThrow();
user.setUsername(userDetails.getUsername());
user.setPassword(userDetails.getPassword());
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
return "User deleted successfully!";
}
}
Step 6: Run the Application
Run the application using your IDE or the terminal:
mvn spring-boot:run
Test the APIs using Postman or any REST client.
Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.
Post a Comment for "CRUD and Authentication with Spring Boot and MySQL"