Building RESTful CRUD Services with Spring Boot and MyBatis

Environment Setup

Database Schema

Create a MySQL database named springboot and a table t_user to hold user records.

CREATE DATABASE `springboot`;
USE `springboot`;

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id`   INT(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
  `name` VARCHAR(10) DEFAULT NULL COMMENT 'User name',
  `age`  INT(2) DEFAULT NULL COMMENT 'Age',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;

Maven Dependencies

Define the parent POM and required starters. The project relies on spring-boot-starter-web, spring-boot-starter-data-jpa, mybatis-spring-boot-starter, and the MySQL connector.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <java.version>1.8</java.version>
    <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis-spring-boot.version}</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>
    <!-- Additional starters: devtools, test, thymeleaf, data-jpa -->
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

Application Configuration

Place connection and MyBatis settings inside application.properties.

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

mybatis.type-aliases-package=com.pancm.bean
mybatis.mapper-locations=classpath:mapper/*.xml

Project Structure

com.pancm
├── bean          # Entity classes
├── dao           # MyBatis mapper interfaces
├── service       # Business logic interfaces & implementations
├── web           # REST controllers
└── Application.java

Implementation Details

Entity Definition

package com.pancm.bean;

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

    public User() {}

    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
}

Data Access Layer

Use MyBatis annotations directly on a mapper interface to avoid XML configuration.

package com.pancm.dao;

import com.pancm.bean.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserDao {

    @Insert("INSERT INTO t_user(id, name, age) VALUES (#{id}, #{name}, #{age})")
    int insert(User user);

    @Update("UPDATE t_user SET name=#{name}, age=#{age} WHERE id=#{id}")
    int update(User user);

    @Delete("DELETE FROM t_user WHERE id=#{id}")
    int deleteById(@Param("id") Integer id);

    @Select("SELECT id, name, age FROM t_user WHERE name=#{name}")
    User selectByName(@Param("name") String name);

    @Select("SELECT id, name, age FROM t_user")
    List<User> selectAll();
}

Service Layer

Define a service interafce and its implementation that delegates to the DAO.

package com.pancm.service;

import com.pancm.bean.User;
import java.util.List;

public interface UserService {
    boolean add(User user);
    boolean modify(User user);
    boolean remove(Integer id);
    User findByName(String name);
    List<User> listAll();
}
package com.pancm.service.impl;

import com.pancm.bean.User;
import com.pancm.dao.UserDao;
import com.pancm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public boolean add(User user) {
        return userDao.insert(user) > 0;
    }

    @Override
    public boolean modify(User user) {
        return userDao.update(user) > 0;
    }

    @Override
    public boolean remove(Integer id) {
        return userDao.deleteById(id) > 0;
    }

    @Override
    public User findByName(String name) {
        return userDao.selectByName(name);
    }

    @Override
    public List<User> listAll() {
        return userDao.selectAll();
    }
}

REST Controller

Expose endpoints that follow REST conventions using appropriate HTTP methods.

package com.pancm.web;

import com.pancm.bean.User;
import com.pancm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public boolean create(@RequestBody User user) {
        System.out.println("Creating user...");
        return userService.add(user);
    }

    @PutMapping
    public boolean update(@RequestBody User user) {
        System.out.println("Updating user...");
        return userService.modify(user);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        System.out.println("Deleting user with id " + id);
        return userService.remove(id);
    }

    @GetMapping
    public User find(@RequestParam String name) {
        System.out.println("Querying user by name: " + name);
        return userService.findByName(name);
    }

    @GetMapping("/all")
    public List<User> list() {
        System.out.println("Fetching all users...");
        return userService.listAll();
    }
}

Application Entry Point

Configure scanning and launch the embedded server.

package com.pancm;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.pancm.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        System.out.println("Service is running...");
    }
}

Testing the Endpoints

After starting Application, use a tool like Postman or curl to verify each operation:

  • GET /api/user/all returns all users.
  • GET /api/user?name=Alice fetches a specific user.
  • POST /api/user with a JSON body creates a new user.
  • PUT /api/user updates an existing record.
  • DELETE /api/user/5 removes the user with id 5.

Each request interacts with the MySQL database through MyBatis and returns JSON responses thanks to @RestController.

Tags: SpringBoot REST MyBatis CRUD MySQL

Posted on Fri, 04 Sep 2026 16:48:03 +0000 by krishnam1981