How to Build a SpringBoot + MyBatis CRUD Project with PageHelper: Step‑by‑Step Guide
Step‑by‑step tutorial showing how to set up MySQL, configure a SpringBoot project, add dependencies, use PageHelper for pagination, generate MyBatis code with MyBatis Generator, and implement CRUD REST APIs for product brands in a Java backend.
MySQL Database Environment Setup
Download and install MySQL 5.7 from the official site.
Set database username and password: root / root.
Download and install Navicat client.
Create database
mall.
Import the mall SQL script from the GitHub repository.
Project Framework Overview
SpringBoot
SpringBoot enables rapid construction of Spring‑based web applications with embedded containers like Tomcat; run the application via the main method.
PageHelper
MyBatis pagination plugin; a few lines of code enable pagination, automatically integrating with SpringBoot when PageHelper is added.
<code>PageHelper.startPage(pageNum, pageSize);
List<PmsBrand> brandList = brandMapper.selectByExample(new PmsBrandExample());
PageInfo<PmsBrand> pageInfo = new PageInfo<>(brandList);
</code>Druid
Alibaba's open‑source database connection pool, claimed to be the best in Java.
MyBatis Generator
Generates model, mapper XML, mapper interfaces, and Example classes from the database, reducing manual mapper code.
Project Setup
Initialize a SpringBoot project with IDEA
Add Project Dependencies
<code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- other dependencies: actuator, aop, pagehelper, druid, mybatis‑generator, mysql‑connector‑java -->
</dependencies>
</code>Configure SpringBoot (application.yml)
<code>server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis:
mapper-locations: classpath*:com/**/mapper/*.xml
</code>Project Structure
MyBatis Generator Configuration
<code><generatorConfiguration>
<properties resource="generator.properties"/>
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.connectionURL}"
userId="${jdbc.userId}"
password="${jdbc.password}">
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model"
targetProject="mall-tiny-01/src/main/java"/>
<sqlMapGenerator targetPackage="com.macro.mall.tiny.mbg.mapper"
targetProject="mall-tiny-01/src/main/resources"/>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.macro.mall.tiny.mbg.mapper"
targetProject="mall-tiny-01/src/main/java"/>
<table tableName="pms_brand"/>
</context>
</generatorConfiguration>
</code>Run Generator Main Function
<code>public class Generator {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
for (String warning : warnings) {
System.out.println(warning);
}
}
}
</code>Add MyBatis Java Configuration
<code>@Configuration
@MapperScan("com.macro.mall.tiny.mbg.mapper")
public class MyBatisConfig {}
</code>Implement Controller Endpoints
<code>@Controller
@RequestMapping("/brand")
public class PmsBrandController {
@Autowired
private PmsBrandService demoService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsBrand>> getBrandList() {
return CommonResult.success(demoService.listAllBrand());
}
@RequestMapping(value = "create", method = RequestMethod.POST)
@ResponseBody
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
int count = demoService.createBrand(pmsBrand);
if (count == 1) {
LOGGER.debug("createBrand success: {}", pmsBrand);
return CommonResult.success(pmsBrand);
} else {
LOGGER.debug("createBrand failed: {}", pmsBrand);
return CommonResult.failed("Operation failed");
}
}
// update, delete, list (paged), get by id methods omitted for brevity
}
</code>Add Service Interface
<code>public interface PmsBrandService {
List<PmsBrand> listAllBrand();
int createBrand(PmsBrand brand);
int updateBrand(Long id, PmsBrand brand);
int deleteBrand(Long id);
List<PmsBrand> listBrand(int pageNum, int pageSize);
PmsBrand getBrand(Long id);
}
</code>Service Implementation
<code>@Service
public class PmsBrandServiceImpl implements PmsBrandService {
@Autowired
private PmsBrandMapper brandMapper;
@Override
public List<PmsBrand> listAllBrand() {
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public int createBrand(PmsBrand brand) {
return brandMapper.insertSelective(brand);
}
@Override
public int updateBrand(Long id, PmsBrand brand) {
brand.setId(id);
return brandMapper.updateByPrimaryKeySelective(brand);
}
@Override
public int deleteBrand(Long id) {
return brandMapper.deleteByPrimaryKey(id);
}
@Override
public List<PmsBrand> listBrand(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return brandMapper.selectByExample(new PmsBrandExample());
}
@Override
public PmsBrand getBrand(Long id) {
return brandMapper.selectByPrimaryKey(id);
}
}
</code>Project Source Code
https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-01
Recommended Reading
mall architecture and feature overview
mall learning prerequisite knowledge (recommended resources)
Welcome to follow, give a like
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.