Step-by-Step Guide to Building a Spring Boot MyBatis Demo Project
This article provides a detailed tutorial for creating a Spring Boot project with MyBatis, including environment setup, Maven dependencies, configuration files, database creation, MyBatis generator usage, and sample controller, service, and mapper code, enabling pagination with PageHelper and testing via HTTP requests.
This guide walks through creating a Spring Boot application that uses MyBatis for data persistence, covering all required tools, dependencies, configuration files, and code.
Environment : IntelliJ IDEA 2017.1.3, Spring Boot 1.5.6, JDK 1.8.0_161, Maven 3.3.9.
pom.xml dependencies (excerpt):
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>application.yml (excerpt):
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/depot
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
mybatis:
mapper-locations: classpath:mapping/*.xml
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSqlDatabase schema (MySQL):
CREATE DATABASE mytest;
CREATE TABLE t_user(
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;MyBatis Generator configuration (excerpt):
<generatorConfiguration>
<classPathEntry location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root"/>
<javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java" enableSubPackages="true" trimStrings="true"/>
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources" enableSubPackages="true"/>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java" enableSubPackages="true"/>
<table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>Generated Java model (User.java) :
package com.winter.model;
public class User {
private Integer userId;
private String userName;
private String password;
private String phone;
// getters and setters omitted for brevity
}Generated Mapper interface (UserMapper.java) :
package com.winter.mapper;
import com.winter.model.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAllUser();
}Mapper XML (UserMapper.xml) (excerpt):
<mapper namespace="com.winter.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.winter.model.User">
<id column="user_id" property="userId" jdbcType="INTEGER"/>
<result column="user_name" property="userName" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="phone" property="phone" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">user_id, user_name, password, phone</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
SELECT <span style="color: #ff0000;"><include refid="Base_Column_List"/></span>
FROM t_user WHERE user_id = #{userId,jdbcType=INTEGER}
</select>
<select id="selectAllUser" resultMap="BaseResultMap">
SELECT <span style="color: #ff0000;"><include refid="Base_Column_List"/></span>
FROM t_user
</select>
<!-- other CRUD statements omitted -->
</mapper>Spring Boot main class :
package com.winter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.winter.mapper")
public class SpringbootMybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}Controller and Service (excerpt):
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping(value="/add", produces="application/json;charset=UTF-8")
public int addUser(User user) { return userService.addUser(user); }
@ResponseBody
@RequestMapping(value="/all/{pageNum}/{pageSize}", produces="application/json;charset=UTF-8")
public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
return userService.findAllUser(pageNum, pageSize);
}
}
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int addUser(User user) { return userMapper.insertSelective(user); }
@Override
public List<User> findAllUser(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectAllUser();
}
}Testing : Use an HTTP client (e.g., IntelliJ HTTP request feature) to POST a JSON user to /user/add and GET /user/all/1/10 to verify pagination and data retrieval.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
