Skip to content

Accessing data with MySQL :: Learn how to set up and manage user accounts on MySQL and how to configure Spring Boot to connect to it at runtime.

License

Notifications You must be signed in to change notification settings

spring-guides/gs-accessing-data-mysql

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

186 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

This guide walks you through the process of creating a Spring application connected to a MySQL Database (as opposed to an in-memory, embedded database, which most of the other guides and many sample applications use). It uses Spring Data JPA to access the database, but this is only one of many possible choices (for example, you could use plain Spring JDBC).

What You Will Build

You will create a MySQL database, build a Spring application, and connect it to the newly created database.

Note
MySQL is licensed with the GPL, so any program binary that you distribute with it must use the GPL, too. See the GNU General Public License.

Setting up the MySQL Database

Before you can build your application, you first need to configure a MySQL database. https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/docker_compose_support.adoc

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

To manually initialize the project:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Spring Web, Spring Data JPA, MySQL Driver, Docker Compose Support, and Testcontainers.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.

Create the @Entity Model

You need to create the entity model, as the following listing (in src/main/java/com/example/accessingdatamysql/User.java) shows:

link:complete/src/main/java/com/example/accessingdatamysql/User.java[role=include]

Hibernate automatically translates the entity into a table.

Create the Repository

You need to create the repository that holds user records, as the following listing (in src/main/java/com/example/accessingdatamysql/UserRepository.java) shows:

link:complete/src/main/java/com/example/accessingdatamysql/UserRepository.java[role=include]

Spring automatically implements this repository interface in a bean that has the same name (with a change in the case — it is called userRepository).

Create a Controller

You need to create a controller to handle HTTP requests to your application, as the following listing (in src/main/java/com/example/accessingdatamysql/MainController.java) shows:

link:complete/src/main/java/com/example/accessingdatamysql/MainController.java[role=include]
Note
The preceding example explicitly specifies POST and GET for the two endpoints. By default, @RequestMapping maps all HTTP operations.

Create an Application Class

Spring Initializr creates a simple class for the application. The following listing shows the class that Initializr created for this example (in src/main/java/com/example/accessingdatamysql/AccessingDataMysqlApplication.java):

link:initial/src/main/java/com/example/accessingdatamysql/AccessingDataMysqlApplication.java[role=include]

For this example, you need not modify the AccessingDataMysqlApplication class.

Spring Initializr adds the @SpringBootApplication annotation to our main class. @SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration: Tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration: Spring Boot attempts to automatically configure your Spring application based on the dependencies that you have added.

  • @ComponentScan: Tells Spring to look for other components, configurations, and services. If specific packages are not defined, recursive scanning begins with the package of the class that declares the annotation.

Run the Application

At this point, you can now run the application to see your code in action. You can run the main method through your IDE or from the command line. Note that, if you have cloned the project from the solution repository, your IDE may look in the wrong place for the compose.yaml file. You can configure your IDE to look in the correct place or you could use the command line to run the application. The ./gradlew bootRun and ./mvnw spring-boot:run commands launch the application and automatically find the compose.yaml file.

Test the Application

Now that the application is running, you can test it by using curl or some similar tool. You have two HTTP endpoints that you can test:

GET localhost:8080/demo/all: Gets all data. POST localhost:8080/demo/add: Adds one user to the data.

The following curl command adds a user:

$ curl http://localhost:8080/demo/add -d name=First -d [email protected]

The reply should be as follows:

Saved

The following command shows all the users:

$ curl http://localhost:8080/demo/all

The reply should be as follows:

[{"id":1,"name":"First","email":"[email protected]"}]

If you run the executable JAR using the java -jar command, docker compose support is no longer available. We need to make an update to our app so that it can connect to the MYSQL container defined in compose.yaml.

First, we need to expose the 3306 port outside the container: edit compose.yaml and adapt the ports section to 3306:3306. The end result should look as follows:

link:complete/compose.yaml[role=include]

Then, you need to configure the application to connect to the database. The URL, username, and password should match the credentials in the docker service configuration. We should also configure spring.jpa.hibernate.ddl-auto to create (or update) the database on startup if required.

link:complete/src/main/resources/application.properties[role=include]

Before running the application, you also need to start the MySQL container as Spring Boot’s docker compose no longer does that for you:

docker compose up -d

You can then run the curl commands as described in [_test_the_application].

Make Some Security Changes

When you are on a production environment, you may be exposed to SQL injection attacks. A hacker may inject DROP TABLE or any other destructive SQL commands. So, as a security practice, you should make some changes to your database before you expose the application to your users.

The following command revokes all the privileges from the user associated with the Spring application:

mysql> revoke all on mydatabase.* from 'myuser'@'%';

Now the Spring application cannot do anything in the database.

The application must have some privileges, so use the following command to grant the minimum privileges the application needs:

mysql> grant select, insert, delete, update on mydatabase.* to 'myuser'@'%';

Removing all privileges and granting some privileges gives your Spring application the privileges necessary to make changes to only the data of the database and not the structure (schema).

When you want to make changes to the database:

  1. Regrant permissions.

  2. Change the spring.jpa.hibernate.ddl-auto to update.

  3. Re-run your applications.

Then repeat the two commands shown here to make your application safe for production use again. Better still, use a dedicated migration tool, such as Flyway or Liquibase.

Summary

Congratulations! You have just developed a Spring application that is bound to a MySQL database and is ready for production!

About

Accessing data with MySQL :: Learn how to set up and manage user accounts on MySQL and how to configure Spring Boot to connect to it at runtime.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 25

Languages