“Java” Spring Boot with MySQL: Database Integration

sametklou

“Java” Spring Boot with MySQL: Database Integration

In this tutorial, we will learn how to integrate MySQL database with a Spring Boot application using Java. We will cover the necessary steps to set up the database connection, create entities, repositories, and services, as well as perform CRUD operations.

Setting Up MySQL Database

To get started, you will need to have a MySQL database server running. Once you have set up the database, you will need to add the MySQL dependency to your pom.xml file:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>

Creating Entity

Next, we will create an entity class that corresponds to a table in the database. For example, let's create a User entity:

@Entity
@Table(name = "users")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String username;
    
    @Column(nullable = false)
    private String email;
    
    // Getters and setters
}

Creating Repository

Now, we will create a repository interface that extends the JpaRepository interface provided by Spring Data JPA. This interface will allow us to perform CRUD operations on the User entity:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    // Additional custom query methods can be added here
}

Creating Service

Next, we will create a service class that will handle business logic and interact with the repository. For example, let's create a UserService class:

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    // Other CRUD operations can be defined here
}

Testing the Application

Finally, we can test our application by creating a REST controller that will expose endpoints for performing CRUD operations on the User entity:

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    // Other CRUD endpoints can be defined here
}

By following these steps, you should now have a Spring Boot application successfully integrated with a MySQL database. You can further expand upon this by adding more entities, repositories, and services to your application. Happy coding!