Using MySQL JDBC Driver With Spring Boot

In this article, I will show you how to connect a MySQL database with your Spring Boot application.

All the code is available on Github

Tools used in this article include:

  • Spring Boot 1.5.6 Release
  • MySQL 5.7.X
  • Maven
  • Java 8
  • Spring Data JPA

1 – Project Structure

The project structure is a typical Maven structure.

Project structure Maven

2 – Project Dependencies

Please note that the parent needs to declared. If you are using Spring Tool Suite, you can click new “Spring Starter Project” and it will populate this for you.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


	<description>mysql jdbc driver example</description>

		<relativePath/> <!-- lookup parent from repository -->






3 – Model

For this example application, our application will be “tracking” the last security audit of systems within a network. As this example application is meant to be simple, there will be minimal fields for the model.

Please note that there is a built in System class in the Java library. For this reason, I would avoid using as a class name for a real application.

package com.michaelcgood.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class System {

	private String name;
	private Date lastaudit;
	public Date getLastaudit() {
		return lastaudit;
	public void setLastaudit(Date lastaudit) {
		this.lastaudit = lastaudit;
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	public long getId() {
		return id;
	public void setId(long id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String toString(){
		return id+" | " + name+ " | "+ lastaudit;

4 – Repository

This is a simple CrudRepository, which is an interface that allows us to do CRUD (Create, Read, Update, Delete) operations.

package com.michaelcgood.dao;

import org.springframework.stereotype.Repository;
import com.michaelcgood.model.System;

public interface SystemRepository extends CrudRepository<System,Long> {


5 – Database Initialization

Spring Boot enables the dataSource initializer by default and loads SQL scripts (schema.sql and data.sql) from the root of the classpath.


Here we create the SQL file that our application will use for the Table schema.


  name VARCHAR(100) NOT NULL,
  lastaudit DATE NOT NULL,
  PRIMARY KEY (id));


We insert example values into our database.


INSERT INTO system(name,lastaudit)VALUES('Windows Server 2012 R2 ','2017-08-11');
INSERT INTO system(name,lastaudit)VALUES('RHEL 7','2017-07-21');
INSERT INTO system(name,lastaudit)VALUES('Solaris 11','2017-08-13');


This XML file is used to configure our logging.


<?xml version="1.0" encoding="UTF-8"?>

    <statusListener class="ch.qos.logback.core.status.NopStatusListener" />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
                %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n

    <logger name="org.springframework.jdbc" level="error" additivity="false">
        <appender-ref ref="STDOUT"/>

    <logger name="com.michaelcgood" level="error" additivity="false">
        <appender-ref ref="STDOUT"/>

    <root level="error">
        <appender-ref ref="STDOUT"/>


6 – Configuration

We configure our datasource and JPA settings.

#==== connect to mysql ======#
spring.datasource.driver-class-name=com.mysql.jdbc.Driver = org.hibernate.dialect.MySQL5Dialect

7 – @SpringBootApplication

CommandLineRunner is implemented in order to execute command line arguments for this example.


import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;

import com.michaelcgood.dao.SystemRepository;

public class MysqlJdbcDriverApplication implements CommandLineRunner {

	DataSource dataSource;

	SystemRepository systemRepository;

	public static void main(String[] args) {, args);

	public void run(String... args) throws Exception {
		System.out.println("Our DataSource is = " + dataSource);
		Iterable<com.michaelcgood.model.System> systemlist = systemRepository.findAll();
		for(com.michaelcgood.model.System systemmodel:systemlist){
			System.out.println("Here is a system: " + systemmodel.toString());



8 – Demo

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 :: Spring Boot ::        (v1.5.6.RELEASE)

Our DataSource is = org.apache.tomcat.jdbc.pool.DataSource@40f70521{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=com.mysql.jdbc.Driver; maxActive=100; maxIdle=100; minIdle=10; initialSize=10; maxWait=30000; testOnBorrow=true; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=********; url=jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false; username=root; validationQuery=SELECT 1; validationQueryTimeout=-1; validatorClassName=null; validationInterval=3000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=false; removeAbandonedTimeout=60; logAbandoned=false; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; suspectTimeout=0; alternateUsernameAllowed=false; commitOnReturn=false; rollbackOnReturn=false; useDisposableConnectionFacade=true; logValidationErrors=false; propagateInterruptState=false; ignoreExceptionOnPreLoad=false; useStatementFacade=true; }
Here is a system: 1 | Windows Server 2012 R2  | 2017-08-11 00:00:00.0
Here is a system: 2 | RHEL 7 | 2017-07-21 00:00:00.0
Here is a system: 3 | Solaris 11 | 2017-08-13 00:00:00.0

The full code is on Github

Published by Michael

I started my website in 2017 to help people learn more about information technology in order to help them become more successful in their careers. I earned my bachelor's degree from New York University, have been working in cyber security since 2012, and live in the Washington D.C. Metro area. I have found running a blog to be one of the greatest assets in helping my career and have found it could even bring in a few extra bucks each month. Starting a blog is easy and rewarding. To keep my knowledge current, I take courses on Udemy and Treehouse. By using my links, you can get a discount on both.

Leave a comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: