Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrate MyBatis with Spring Boot to Implement Relational Database Query Operations

Tech 1

Database Environment Preparation

Use a MySQL 8.x instance to create the required business table. You can import pre-written SQL scripts via database management tools like Navicat or DBeaver to generate the student information table, and adjust field definitions based on actual business requirements.

Project Initialization and Dependency Configuration

Create a Spring Boot project via Spring Initializr or IDE scaffolding, then add the following core dependencies to your pom.xml:

<!-- MyBatis Spring Boot Starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.3.1</version>
</dependency>
<!-- MySQL JDBC Driver -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

MyBatis Code Generation Configuration

  1. Add the MyBatis Generator configuration file (named generatorConfig.xml by default) to the project root directory, modify the JDBC driver local path, target packages for generated entity classes, Mapper interfaces and XML files to match your project structure.
  2. Add the MyBatis Generator Maven plugin to the build plugin section of pom.xml:
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.4.2</version>
    <configuration>
        <configurationFile>generatorConfig.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
</plugin>
  1. Run the plugin via Maven command or IDE plugin panel to generate required entity classes, Mapper interfaces and corresponding SQL XML files.
  2. Add the @MapperScan("com.yourproject.mapper") annotation to the main Spring Boot startup class, replace the package path with your actual Mapper interface storage path to avoid manually adding @Mapper annotations to each Mapper interface.

Business Logic Development

Create service, service.impl and controller packages under the project base package to layer business code:

  1. Define the student business service interface under the service package:
package com.yourproject.service;

import com.yourproject.model.Student;

public interface StudentService {
    /**
     * Query student details by student ID
     * @param studentId Unique ID of the student
     * @return Student entity object
     */
    Student getStudentById(Integer studentId);
}
  1. Implement the service interface under the service.impl package:
package com.yourproject.service.impl;

import com.yourproject.mapper.StudentMapper;
import com.yourproject.model.Student;
import com.yourproject.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Student getStudentById(Integer studentId) {
        return studentMapper.selectByPrimaryKey(studentId);
    }
}
  1. Create the query controller under the controller package:
package com.yourproject.controller;

import com.yourproject.model.Student;
import com.yourproject.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/student")
public class StudentQueryController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/get")
    public Student queryStudentInfo(@RequestParam Integer id) {
        return studentService.getStudentById(id);
    }
}

Application Configuraton

Add the following configuration to the application.properties file:

# Embedded Tomcat port configuration
server.port=9003
# Application context path
server.servlet.context-path=/springboot-mybatis-demo
# Datasource configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_demo?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=your_db_password

Resource Compilation Configuration

To ensure Mapper XML files stored under the src/main/java directory are correctly compiled to the classpath, add the following resource scanning configuration to the build section of pom.xml:

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*</include>
        </includes>
    </resource>
</resources>

Function Verification

Start the Spring Boot application, send a GET request to http://localhost:9003/springboot-mybatis-demo/api/student/get?id=1, corresponding student information will be returned in JSON format if the configuration is correct.

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.