Site icon LCDUNG

Config Spring boot work with MySQL

How to config  spring boot work with MySQL? Spring Boot is very easy to use with the H2 Database. If the H2 database is found on your class path, Spring Boot will automatically set up an in memory H2 database for your use. If you want to use MySQL? Naturally, Spring Boot has support for MySQL and a number of other popular relational databases.

Let’s say we want to deploy this application to production and we’ve decided to use MySQL for the database. Changing Spring Boot from H2 to MySQL is easy to do if you read post Giới thiệu về Spring Boot. Spring Boot là gì?.

MySQL Configuration

For this example, I’m using MySQL installed locally. You’ll need to have a database defined for your use. For this example, I want to create a database for my use. Using the command prompt, you can log into MySQL and create a database width commend below:

You only need to use these commands if you want to use a new database. MySQL is a very robust database.

MySQL Dependencies

First we need to add the MySQL database drivers to our project. You will need to add the following dependency to your Maven POM file.

POM.xml

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

Spring Boot Properties

We need to override the H2 database properties being set by default in Spring Boot. The nice part is, Spring Boot sets default database properties only when you don’t. So, when we configure MySQL for use. Spring Boot wont setup the H2 database anymore.

The following properties are need to configure MySQL with Spring Boot. You can see these are pretty standard Java data source properties. Since in my example project, I’m using JPA too, we need to configure Hibernate for MySQL too.

NOTE: If this was actually a production database, you not tell Hibernate to use the create-drop option. This tells Hibernate to recreate the database on startup. Definitely not the behavior we want. You can set this property to the following values: none, validate, update, create-drop. If this was actually a production database, you probably would want to use validate.

Running Spring Boot with MySQL

This is all that needs to be changed to use MySQL with Spring Boot. When you start the project now, MySQL will be used by the Spring Boot application for the database. And run command run it.

mvn spring-boot:run

Remember run MySQL before run spring boot.

Download sample here: https://github.com/lechidung/config-spring-boot-work-with-mysql

Access page after run

Access H2 to config DB

 

 

Exit mobile version