Boost Your Spring Boot APIs with MyBatisPlusPro: A Step‑by‑Step Guide
This tutorial shows how to extend MyBatisPlus with a reusable BaseController, create utility methods for naming conversion and query building, configure pagination support, and quickly generate CRUD REST endpoints in Spring Boot projects using MyBatisPlusPro.
Using MyBatisPlus for data access is convenient, but most examples only cover DAO‑level CRUD. This guide introduces MyBatisPlusPro, which provides a ready‑to‑use BaseController that supplies CRUD, list, pagination, sorting, parameterized queries, and count operations simply by extending a generic class.
Step 1: Add MyBatisPlus dependency
<code><dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency></code>Step 2: Write utility class
<code>/**
* Apprentice system utilities
*/
public class ApprenticeUtil {
private static Pattern humpPattern = Pattern.compile("[A-Z]");
private static Pattern linePattern = Pattern.compile("_(\\w)");
/** Convert camelCase to snake_case */
public static String humpToLine(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** Convert snake_case to camelCase */
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** Build QueryWrapper from an entity */
public static <E> QueryWrapper<E> getQueryWrapper(E entity) {
Field[] fields = entity.getClass().getDeclaredFields();
QueryWrapper<E> query = new QueryWrapper<>();
for (Field field : fields) {
if (Modifier.isFinal(field.getModifiers())) continue;
field.setAccessible(true);
try {
Object value = field.get(entity);
if (!ObjectUtils.isEmpty(value)) {
String name = humpToLine(field.getName());
query.eq(name, value);
}
} catch (IllegalAccessException e) {
return null;
}
}
return query;
}
/** Get field value via reflection */
public static <E> Object getValueForClass(E entity, String value) {
try {
Field field = entity.getClass().getDeclaredField(value);
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), entity.getClass());
Method getter = pd.getReadMethod();
return ReflectionUtils.invokeMethod(getter, entity);
} catch (NoSuchFieldException | IntrospectionException e) {
e.printStackTrace();
return null;
}
}
}
</code>Step 3: Write BaseController class
<code>/** Core generic controller */
public class BaseController<S extends IService<E>, E> {
@Autowired
protected S baseService;
@ApiOperation("Insert")
@PostMapping("/insert")
public ResponseUtils insert(@RequestBody E entity) {
baseService.save(entity);
return ResponseUtils.success("Insert successful");
}
@ApiOperation("Delete")
@PostMapping("/deleteById")
public ResponseUtils delete(@RequestBody List<Integer> ids) {
baseService.removeByIds(ids);
return ResponseUtils.success("Delete successful");
}
@ApiOperation("Update")
@PostMapping("/updateById")
public ResponseUtils updateById(@RequestBody E entity) {
baseService.updateById(entity);
return ResponseUtils.success("Update successful");
}
@ApiOperation("Get by ID")
@GetMapping("/getById")
public ResponseUtils getById(@RequestParam Integer id) {
return ResponseUtils.success(baseService.getById(id));
}
@ApiOperation("Save")
@PostMapping("/save")
public ResponseUtils save(@RequestBody E entity) {
baseService.saveOrUpdate(entity);
return ResponseUtils.success("Save successful");
}
@ApiOperation("List")
@PostMapping("/list")
public ResponseUtils list(@RequestBody E entity) {
QueryWrapper<E> wrapper = ApprenticeUtil.getQueryWrapper(entity);
List<E> list = baseService.list(wrapper);
return ResponseUtils.success(list);
}
@ApiOperation("Page")
@PostMapping("/page")
public ResponseUtils page(@RequestBody PageParamDto<E> param) {
if (param.getPage() < 1) param.setPage(1);
if (param.getSize() > 100) param.setSize(100);
Page<E> page = new Page<>(param.getPage(), param.getSize());
QueryWrapper<E> wrapper = new QueryWrapper<>();
if (!StrUtil.isEmpty(param.getAsc()) && !"null".equals(param.getAsc())) {
wrapper.orderByAsc(param.getAsc().split(","));
}
if (!StrUtil.isEmpty(param.getDesc()) && !"null".equals(param.getDesc())) {
wrapper.orderByDesc(param.getDesc().split(","));
}
Page<E> result = baseService.page(page, wrapper);
return ResponseUtils.success(result);
}
@ApiOperation("Count")
@PostMapping("/count")
public ResponseUtils count(@RequestBody E entity) {
QueryWrapper<E> wrapper = ApprenticeUtil.getQueryWrapper(entity);
long cnt = baseService.count(wrapper);
return ResponseUtils.success(cnt);
}
}
</code>Step 4: Configure pagination support
<code>@Configuration
public class MybatisPlusConfig {
/** Set pagination interceptor */
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
</code>Step 5: Extend BaseController in your own controllers
<code>@RestController
@RequestMapping("/apprentice/dynamic")
@Api("Dynamic Management")
public class DynamicController extends BaseController<IDynamicService, Dynamic> {
}
@RestController
@RequestMapping("/apprentice/blog")
@Api(tags = "Blog Management")
public class BlogController extends BaseController<IBlogService, Blog> {
}
</code>After extending BaseController, the CRUD endpoints are available automatically.
Source code repository: https://gitee.com/WangFuGui-Ma/mybatis-plus-pro
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.