Setting up Spring Boot 3 + Maven + MySQL + JDBC Example


In this tutorial we will cover step-by-step how to setup plain JDBC with Spring Boot 3 and Maven and MySQL Database.


Step 1: Downloading the Spring Initializr Project

    Go to start.spring.io and fill in the following information for to download our JDBC project structure.

    Spring initializr setting for Spring Boot 3 + Spring Data JDBC

    Make sure to select Project as Maven and Language as Java, you may choose the latest version of Spring Boot (not Snapshot or Mx versions), for me its 3.0.5

    Do select the Packaging as jar and you may choose any version of Java thats available, I am going with the latest thats Java 20.

    Make sure to click on "Add Dependencies..." and choose Spring Data JDBC

    Once all is set, you can click on, Generate button at the bottom to download the project zip file.


Step 2: Importing the JDBC Project to IDE

    Extract the zip project and open your IDE (Eclipse, IntelliJ, NetBeans or VSCode) to import the project, we will demonstrate using IDEA IntelliJ.


    1. Unzip the project file we downloaded at Step 1.
    2. Open IntelliJ IDE.
    3. Go to Menu: File -> New -> Project From Existing Source...
    4. Now select your project folder and click Open
    5. Keep clicking next, and "Please select project SDK" choose your JDK (in my case JDK 20)
    6. Right-click on your project and select Maven -> Download Sources
Quick alternative: you can close the project and be on the Welcome Screen and click on Open and choose your application folder.

Quick Way To Import Spring Project to IntelliJ

Step 3: Setting up MySQL Database.

    Make sure you have download and installed MySQL Database. We will first create our test database.

    create DATABASE jdbctest;

    Next lets create a simple database table.

    CREATE TABLE `jdbctest`.`message` (`message` VARCHAR(100) NOT NULL ) ENGINE = InnoDB;

    Next, lets insert a record.

    INSERT INTO `message` (`message`) VALUES ('Hello Spring JDBC');

    Finally lets check the record was inserted properly.

    SELECT * FROM message;

    message
    Hello Spring JDBC

    We are all set with the MySQL Database for our tutorial!


Step 4: Configuration for MySQL with Spring Boot

    Open the applications.properties files in your project that you will find under src -> main -> resources and add the below details.

    spring.datasource.url=jdbc:mysql://localhost/jdbctest
    spring.datasource.username=root
    spring.datasource.password=your-db-password-can-be-blank-by-default
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

    Next open the pom.xml file add the MySQL connector dependency.

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

    We are all set with the JDBC configuration!


Step 5: Creating our CommandLineRunner Class

    Let's first create a Pojo Message,

    package org.code2care.springboot.jdbctutorial;
    
    public class Message {
    
        private String message;
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        @Override
        public String toString() {
            return "Message{" +
                    "message='" + message + '\'' +
                    '}';
        }
    }

    Now we are all set for the final class that we need, we call it JDBCRunner


    package org.code2care.springboot.jdbctutorial;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    @Component
    public class JDBCRunner implements CommandLineRunner {
    
        private String query = "Select * from message";
    
        @Autowired
        JdbcTemplate jdbcTemplate;
    
        @Override
        public void run(String... args) throws Exception {
    
           List<Message> messages = jdbcTemplate.query(query, new BeanPropertyRowMapper<>(Message.class));
            System.out.println(messages.get(0).getMessage());
        }
    }

    Code Explanation


    We have created a Java class named JDBCRunner that implements the CommandLineRunner interface which is marked with the Spring @Component annotation so that it is managed by Spring IoC, so it will be automatically detected and instantiated by the Spring framework during runtime.

    The class has a private field named query which is a SQL query to retrieve our "Hello Spring JDBC" message

    The @Autowired annotation is used to inject a JdbcTemplate object into the class. This object is a Spring JDBC abstraction that simplifies the use of JDBC and eliminates the need for boilerplate code.

    As we have implemented the CommandLineRunner interface, so the run method will be executed when the Spring application is started and execute the SQL query and retrieve a list of Message objects.


Step 6: Running your Hello JDBC Project

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap