Showing posts with label SpringBoot MariaDB. Show all posts
Showing posts with label SpringBoot MariaDB. Show all posts

Monday, 9 October 2023

Spring Boot MySQL connection with example

To connect to a MySQL database in Spring Boot, you need to add the following dependencies to your project's pom.xml file:

XML
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Once you have added these dependencies, you need to configure your database connection in the application.properties file. Here is an example:

Properties
spring.datasource.url=jdbc:mysql://localhost:3306/my_database
spring.datasource.username=root
spring.datasource.password=password

Replace the my_database, root, and password values with your own database connection information.

Once you have configured your database connection, you can start using Spring Boot to interact with your MySQL database. For example, you can create a repository interface to access your database tables. Here is an example:

Java
public interface UserRepository extends JpaRepository<User, Long> {

}

This repository interface will allow you to perform CRUD operations on the User table.

You can also use Spring Boot to create Spring Data JPA entities to represent your database tables. Here is an example:

Java
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    // getters and setters omitted for brevity
}

Once you have created your repository interface and entity class, you can start using Spring Boot to interact with your MySQL database. For example, you can inject the UserRepository into a controller and use it to perform CRUD operations on the User table.

Here is an example of a Spring Boot controller that uses the UserRepository:

Java
@Controller
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    // other methods omitted for brevity
}

To start the Spring Boot application, you can use the following command:

mvn spring-boot:run

This will start the application on port 8080. You can then access the application in your web browser at http://localhost:8080/.

This is just a simple example of how to connect to a MySQL database in Spring Boot. You can use Spring Boot to develop a wide variety of applications that interact with MySQL databases.