Spring Boot Jdbc Mysql Example

The Spring Boot Jdbc Mysql Example will show you how to create a Spring Boot JDBC application using MySQL and HikariCP. Our application will accept arguments to perform either “insert” or “query” function. If arguments is “insert” it will insert a row with data input. If arguments is “query” it will query all rows on the table

Other interesting posts you may like

Let’s begin:

Project Structure
In this Spring Boot Jdbc Mysql Example, we create a standard Maven project structure like this

Spring Boot Jdbc Mysql Example

Maven Dependency
Our Spring Boot Jdbc Mysql Example will use JDBC, MySQL and HikariCP connection pool, so that we must add these dependencies in the pom.xml

JDBC Properties Configuration
For example, we have a database schema named javabcyode. We configure JDBC and HikariCP settings in the jdbc.properties file and place that file in the classpath directory

Create Database Table

Create a tenant table using the following script

Initialize data for the tenant table using the script below

Dig deeper: We just have to push two above scripts schema.sql and data.sql in the classpath directory and do nothing. Then Spring Boot will take care to create table and insert data for us. Because Spring boot enables the dataSource initializer by default and loads SQL scripts from the classpath.

Create TenantRepository
We create TenantRepository class and inject JdbcTemplate via @Autowired. This repository takes care of the database side

Create Tenant Model
Our Tenant model is simple like this

Create SpringBootApplication class
Our MyConsoleApplication class implements the CommandLineRunner interface, accept arguments to perform either “insert” or “query” function.

Demo Spring Boot JDBC Application
Go to the project directory in the console

#Packaging jar file

#Run jar file to initialize the database, create the table and insert data and display the datasource information

Run the command to insert a new tenant, don’t for get disable database initialize process
java -Dspring.datasource.initialize=false -jar target/spring-boot-jdbc-1.0.jar insert jdbcUser jdbcPassword

Query all tenants in the database
java -Dspring.datasource.initialize=false -jar target/spring-boot-jdbc-mysql-example-1.0.jar query

That’s all on the Spring Boot Jdbc Mysql Example.

References
Spring Boot – Working with SQL databases
Spring Boot – Database initialization
HikariCP

Download complete source code, click link below

spring-boot-jdbc-mysql-example.zip (7 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons