Configure MySQL for Spring Boot Application

In this post, we will discuss how to configure MySQL for Spring Boot application. We will get into details for the support provided by Spring Boot for MySQL database and steps for configuring MySQL for Spring Boot Application.

Configure MySQL for Spring Boot Application

Spring Boot provides a ready-to-use support for H2 Database.Spring Boot automatically set up in memory H2 database if it detects H2 configurations in the classpath.This is superb to work on the development project, however, most of the enterprise projects use production level databases like MySQL, Oracle, etc.

Spring Boot has support for MySQL and other popular relational databases.In this post, we will focus on configuring Spring Boot for MySQL database.

1. MySQL Database Configuration

I will not cover installing MySQL server on your machine or how to create a new database in the MySQL. For this post, I assume that we have already installed MySQL on your machine.Please create a new database on the MySQL server (Let’s call this new database as javadevjournal).

2. Adding MySQL Dependencies

To enable support for MySQL in our project, we need to add spring-boot-starter-data-jpa and mysql-connector-java starter in the pom.xml file.

<dependencies>
  <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
  <!-- Use MySQL Connector-J -->
   <dependency>
      <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
<dependencies>

Spring Boot auto-configure DataSource if spring-boot-starter-data-jpa is in the class-path by reading database configurations defined in the application.properties.

3. Configure MySQL Using Spring Boot Properties

By Default, Spring Boot provides database configurations for the H2 database.To use MySQL for our application, we need to override these default configurations.Once we define DB properties in the project’s application.properties file, Spring Boot will not set up default database anymore.

spring.datasource.url=jdbc:mysql://localhost:3306/javadevjournal
spring.datasource.username=javadevjournal
spring.datasource.password=ThePassword
spring.jpa.hibernate.ddl-auto=update

## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

The property spring.jpa.hibernate.ddl-auto is for database initialization. It is good security practice that after your database is in production state, you make this none. Here are some commonly used ddl values:

  • none: The default for MySQL. We make no change to the database structure.
  • update: Hibernate changes the database according to the entity structures.
  • create: Creates the database every time but does not drop it on close.
  • create-drop: Creates the database and drops it when SessionFactory closes.

While setting up JPA properties, We need not specify the driver or the dialect. These are detected automatically. If you want to customize these properties, feel free to add/customize using application.properties file.

These are the only configuration changes required to use MySQL with your Spring Boot application.Once you start your application, Spring Boot will use MySQL as your underlying database.

Next section is optional and provide a working example as how to configure MySQL for Spring Boot application and save data in the databases with help of Spring JPA.

4. Create JPA Entity

To save data in the database using the Spring JPA, we need to create an entity model. Let’s create a User entity which will store the data in the database.This is how our entity will look like:

@Entity
@Table(name = "user")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    @Column(unique = true)
    private String email;
    private String password;

    //getter setters
}

Hibernate will automatically convert this entity to the underlying table in the MySQL Database. The next step is to create the repository.This will help us to execute normal CRUD operation in the database.We are using the Spring repository interface which generate the required mapping for us and helps us avoid writing boilerplate code.

5. Create User Repository

@Repository
public interface UserRepository extends JpaRepository < UserEntity, Long > {
    UserEntity findByEmail(String email);
}

This is an interface and we extending the JpaRepository. Spring will automatically create a bean for this entry (bean name as userRepository) and provide implementations for the CURD operations.The next step is to create a simple spring mvc controller and call the userRepositry to save information in the database.

6. User Controller

Let’s create a simple user controller to interact with our userRepository

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.javadevjournal.core.user.jpa.repository.UserRepository;
import com.javadevjournal.core.user.jpa.data.UserEntity;

@Controller
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping(path = "/add")
    public @ResponseBody String addNewUser(@RequestParam String firstName, @RequestParam String firstName, @RequestParam String email) {

        UserEntity user = new UserEntity();
        user.setFirstName(firstName);
        user.setLastName(firstName);
        user.setEmail(email);
        userRepository.save(user);
        return "User Created";
    }

    @GetMapping(path = "/all")
    public @ResponseBody Iterable < User > getAllUsers() {
        return userRepository.findAll();
    }

}

If we run our application, we can create users in the database by calling the /user/add with request parameters and can get all users by calling /all method.

7. Testing Application

To test our application, we can either use Postman or simple curl command. Run the following curl command to create user in the database.

$ curl localhost:8080/user/add -d firstName=Java -d lastName=DevJournal -d [email protected]

To get the list of all saved customer in the database, run the following curl command

$ curl 'localhost:8080/user/all'

8. Spring Boot 3 with MySQL

Most of the article hold true when configuring Spring Boot with Mysql, however there are few changes that were done with Spring Boot 3 in terms on dependencies and other changes.

  • Spring Boot 3 uses Hibernate 6 and there is change in Hibernate 6 on how dialects works.
  • dialects containing InnoDB in their name were removed in Hibernate 6,

If you are migrating or setting up, make sure to use the following property in the dialect

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

Summary

In this short post, we covered configure MySQL for Spring Boot application.We learned how to override default data source configurations provided by Spring Boot to use MySQL as the underlying database.The source code is available on our GitHub Repository

Comments are closed.