Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Auto-Configuration of JDBC Components in Spring Boot JDBC Integration

Tech 2

Project Initialization and Database Setup

Use MySQL as the datasource for this integration, create the required database and table first:

CREATE DATABASE springboot_demo CHARACTER SET 'utf8mb4';

CREATE TABLE t_user(
	id INT(11) NOT NULL AUTO_INCREMENT,
	name VARCHAR(20) NOT NULL,
	tel VARCHAR(20) NULL,
	PRIMARY KEY (id)
);

Add Project Dependencies

Add the required dependencies for JDBC integration and MySQL connection to your Maven project:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
</dependencies>

Configure Datasource Propertise

Create an application.properties file under the src/main/resources directory, and add the following datasource configuration:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456

Implement Business Code

Entity Class

Create the User entity class mapped to the t_user table:

public class User {
    private Integer id;
    private String name;
    private String contact;

    // Getters, Setters, and toString method omitted
}

Data Access Layer

import org.springframework.stereotype.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void save(User user) {
        jdbcTemplate.update(
            "INSERT INTO t_user (name, tel) VALUES (?, ?)",
            user.getName(), user.getContact()
        );
    }

    public List<User> getAllUsers() {
        return jdbcTemplate.query(
            "SELECT id, name, tel AS contact FROM t_user",
            BeanPropertyRowMapper.newInstance(User.class)
        );
    }
}

Service Layer

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    public void testTransactionQuery() {
        User newUser = new User();
        newUser.setName("Qi Tian Da Sheng");
        newUser.setContact("12306");
        userDao.save(newUser);
        List<User> userList = userDao.getAllUsers();
        userList.forEach(System.out::println);
    }
}

Main Application Class

Add the main entry point, enable annotation-driven transaction management, and trigger the test method after context initialization:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
@EnableTransactionManagement
public class JdbcDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(JdbcDemoApplication.class, args);
        UserService userService = applicationContext.getBean(UserService.class);
        userService.testTransactionQuery();
    }
}

Core JDBC Component Autoconfiguration

Spring Boot automatically configures all required JDBC components through two key auto-configuration classes when spring-boot-starter-jdbc is on the classpath:

  1. DataSourceAutoConfiguration: This class is responsible for creating the DataSource bean. It binds external configuration propreties under the spring.datasource prefix, initializes the connection pool, and registers the DataSource to the Spring context. HikariCP is used as the default connection pool implementation in Spring Boot 2.x and above.
  2. JdbcTemplateAutoConfiguration: This configuration is conditional on the existence of a DataSource bean in the context. It automatically creates a singleton JdbcTemplate instance injected with the configured DataSource, and registers it as a bean. This eliminates the need for manual JdbcTemplate configuration, allowing direct injection into data access components.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.