- 添加依赖
<dependency> <groupId>***.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.2</version> <exclusions> <exclusion> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </exclusion> </exclusions> </dependency> <!--解决【Invalid value type for attribute 'factoryBeanObjectType': java.lang.String】--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.3</version> </dependency> <!--<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.32</version> </dependency>--> <dependency> <groupId>***.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
-
配置属性信息
spring: datasource: driver-class-name: ***.mysql.cj.jdbc.Driver username: XXX password: XXX url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai mybatis-plus: mapper-locations: classpath:/mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
-
编写业务逻辑测试代码
package org.coding.java.controller; import ***.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.annotation.Resource; import org.coding.java.api.***monResult; import org.coding.java.domain.user.UserDO; import org.coding.java.query.PageQueryVO; import org.coding.java.service.UserService; import org.springframework.web.bind.annotation.*; import java.util.List; @Tag(name = "用户管理") @RestController @RequestMapping("api/v1/user") public class UserController { @Resource private UserService userService; @PostMapping("/saveUser") @Operation(summary = "新增用户") public ***monResult<Integer> saveUser(@RequestBody UserDO userDO) { return userService.saveUser(userDO); } @DeleteMapping("/deleteUser/{id}") @Operation(summary = "根据ID删除用户") public ***monResult<Integer> deleteUser(@PathVariable("id") Long id) { return userService.deleteUserById(id); } @GetMapping("/selectList") @Operation(summary = "查询用户信息") public ***monResult<List<UserDO>> selectList() { return userService.selectList(); } @PostMapping("/selectPage") @Operation(summary = "分页查询用户信息") public ***monResult<IPage<UserDO>> selectPage(@RequestBody PageQueryVO queryVO) { return userService.selectPage(queryVO); } @PutMapping("/updateUser") @Operation(summary = "更新用户信息") public ***monResult<Integer> updateUser(@RequestBody UserDO userDO) { return userService.updateUser(userDO); } }
package org.coding.java.service.impl; import ***.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import ***.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import ***.baomidou.mybatisplus.core.metadata.IPage; import ***.baomidou.mybatisplus.extension.plugins.pagination.Page; import jakarta.annotation.Resource; import org.coding.java.api.***monResult; import org.coding.java.api.ResponseMessage; import org.coding.java.domain.user.UserDO; import org.coding.java.mapper.UserMapper; import org.coding.java.query.PageQueryVO; import org.coding.java.service.UserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collections; import java.util.List; import java.util.Objects; @Service @Transactional public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public ***monResult<Integer> saveUser(UserDO userDO) { return ***monResult.ok(ResponseMessage.MessageCode.SAVE_SU***ESS.code(), ResponseMessage.MessageCode.SAVE_SU***ESS.message(), userMapper.insert(userDO)); } @Override public ***monResult<Integer> deleteUserById(Long id) { int count = userMapper.deleteById(id); if (count > 0) { return ***monResult.ok(ResponseMessage.MessageCode.DELETE_SU***ESS.code(), ResponseMessage.MessageCode.DELETE_SU***ESS.message(), count); } return ***monResult.failed(ResponseMessage.MessageCode.DELETE_FAILED.code(), ResponseMessage.MessageCode.DELETE_FAILED.message(), count); } @Override public ***monResult<List<UserDO>> selectList() { if (getUserList().size() > 0) { return ***monResult.ok(ResponseMessage.MessageCode.SELECT_SU***ESS.code(), ResponseMessage.MessageCode.SELECT_SU***ESS.message(), getUserList()); } return ***monResult.failed(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), Collections.emptyList()); } @Override public ***monResult<IPage<UserDO>> selectPage(PageQueryVO queryVO) { IPage<UserDO> page = new Page<>(queryVO.getPageNo(), queryVO.getPageSize()); IPage<UserDO> pageList = getUserPageList(queryVO, page); if (pageList.getRecords().size() > 0) { return ***monResult.ok(ResponseMessage.MessageCode.SELECT_SU***ESS.code(), ResponseMessage.MessageCode.SELECT_SU***ESS.message(), pageList); } else if (pageList.getRecords().size() == 0) { return ***monResult.failed(ResponseMessage.MessageCode.SELECT_NON_CONFORMANCE.code(), ResponseMessage.MessageCode.SELECT_NON_CONFORMANCE.message(), pageList); } return ***monResult.failed(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), pageList); } @Override public ***monResult<Integer> updateUser(UserDO userDO) { int update = userMapper.updateById(userDO); if (update > 0) { return ***monResult.ok(ResponseMessage.MessageCode.UPDATE_SU***ESS.code(), ResponseMessage.MessageCode.UPDATE_SU***ESS.message(), update); } return ***monResult.failed(ResponseMessage.MessageCode.UPDATE_FAILED.code(), ResponseMessage.MessageCode.UPDATE_FAILED.message(), update); } private IPage<UserDO> getUserPageList(PageQueryVO queryVO, IPage<UserDO> page) { LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>(); wrapper.like(Objects.nonNull(queryVO.getName()), UserDO::getName, queryVO.getName()); wrapper.eq(Objects.nonNull(queryVO.getPhone()), UserDO::getPhone, queryVO.getPhone()).or(); wrapper.eq(Objects.nonNull(queryVO.getEmail()), UserDO::getEmail, queryVO.getEmail()); return userMapper.selectPage(page, wrapper); } private List<UserDO> getUserList() { QueryWrapper<UserDO> wrapper = new QueryWrapper<>(); wrapper.select("id", "name", "age", "email", "sex", "phone"); return userMapper.selectList(wrapper); } }
-
配置mybatis-plus分页插件
package org.coding.java.config.mybatisplus; import ***.baomidou.mybatisplus.annotation.DbType; import ***.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import ***.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import ***.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * @Description: mybatis常用配置 */ @Configuration @EnableTransactionManagement @MapperScan("org.coding.java.mapper") public class MybatisPlusConfig { /** * 实现分页配置 * @return */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); paginationInnerInterceptor.setDbType(DbType.MYSQL); interceptor.addInnerInterceptor(paginationInnerInterceptor); return interceptor; } }
-
配置mybatis-plus之属性自动填充
package org.coding.java.config.mybatisplus; import ***.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.***ponent; import java.time.LocalDateTime; /** * @Description: mybatis自动填充功能 */ @***ponent public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); } @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); } }
-
如图所示
二、SpringBoot3整合mybatis
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>***.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.coding</groupId>
<artifactId>boot-cmmon</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>***.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<!--解决【Invalid value type for attribute 'factoryBeanObjectType': java.lang.String】-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
2、配置属性
server:
port: 18082
spring:
datasource:
driver-class-name: ***.mysql.cj.jdbc.Driver
username: XXX
password: XXX
url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&serverTimezone=Asia/Shanghai
mybatis:
mapper-locations: classpath:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
pagehelper:
helper-dialect: mysql # 指定数据库类型
reasonable: true
params: count=countSql
support-methods-arguments: true
# springdoc-openapi项目配置
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /v3/api-docs
group-configs:
- group: 'mybatis'
paths-to-match: '/**'
packages-to-scan: org.coding.java.controller
# knife4j的增强配置,不需要增强可以不配
knife4j:
enable: true
setting:
language: zh_***
logging:
level:
org.coding.java.mapper: debug
3、编写测试代码
package org.coding.java.service.impl;
import ***.github.pagehelper.IPage;
import ***.github.pagehelper.PageHelper;
import ***.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.coding.java.api.***monResult;
import org.coding.java.api.ResponseMessage;
import org.coding.java.domain.user.UserDO;
import org.coding.java.mapper.UserMapper;
import org.coding.java.query.QueryPageVO;
import org.coding.java.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
@Override
public ***monResult<Integer> saveUser(UserDO userDO) {
return ***monResult.ok(ResponseMessage.MessageCode.SAVE_SU***ESS.code(), ResponseMessage.MessageCode.SAVE_SU***ESS.message(), userMapper.saveUser(userDO));
}
@Override
public ***monResult<List<UserDO>> selectList() {
List<UserDO> list = userMapper.selectList();
if (list.size() > 0) {
return ***monResult.ok(ResponseMessage.MessageCode.SELECT_SU***ESS.code(), ResponseMessage.MessageCode.SELECT_SU***ESS.message(), list);
}
return ***monResult.ok(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), list);
}
@Override
public ***monResult<Integer> deleteUserById(Long id) {
Integer count = userMapper.deleteUserById(id);
if (count > 0) {
return ***monResult.ok(ResponseMessage.MessageCode.DELETE_SU***ESS.code(), ResponseMessage.MessageCode.DELETE_SU***ESS.message(), count);
}
return ***monResult.ok(ResponseMessage.MessageCode.DELETE_FAILED.code(), ResponseMessage.MessageCode.DELETE_FAILED.message(), count);
}
@Override
public ***monResult<Integer> updateUser(UserDO userDO) {
Integer count = userMapper.updateUser(userDO);
if (count > 0) {
return ***monResult.ok(ResponseMessage.MessageCode.UPDATE_SU***ESS.code(), ResponseMessage.MessageCode.UPDATE_SU***ESS.message(), count);
}
return ***monResult.ok(ResponseMessage.MessageCode.UPDATE_FAILED.code(), ResponseMessage.MessageCode.UPDATE_FAILED.message(), count);
}
@Override
public ***monResult<PageInfo> selectPage(QueryPageVO pageVO) {
PageHelper.startPage(pageVO.getPageNo(), pageVO.getPageSize());
List<UserDO> list = userMapper.selectPage(pageVO);
PageInfo<UserDO> pageInfo = new PageInfo<>(list);
if (pageInfo.getTotal() > 0) {
return ***monResult.ok(ResponseMessage.MessageCode.SELECT_SU***ESS.code(), ResponseMessage.MessageCode.SELECT_SU***ESS.message(), pageInfo);
}
return ***monResult.ok(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), pageInfo);
}
}
package org.coding.java.controller;
import ***.github.pagehelper.IPage;
import ***.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.coding.java.api.***monResult;
import org.coding.java.domain.user.UserDO;
import org.coding.java.query.QueryPageVO;
import org.coding.java.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Resource
private UserService userService;
@PostMapping("/saveUser")
@Operation(summary = "新增用户")
public ***monResult<Integer> saveUser(@RequestBody UserDO userDO) {
return userService.saveUser(userDO);
}
@GetMapping("/selectList")
@Operation(summary = "查询用户【不分页】")
public ***monResult<List<UserDO>> selectList() {
return userService.selectList();
}
@PostMapping("/selectPage")
@Operation(summary = "查询用户【分页】")
public ***monResult<PageInfo> selectPage(@RequestBody QueryPageVO pageVO) {
return userService.selectPage(pageVO);
}
@DeleteMapping("/deleteUserById/{id}")
@Operation(summary = "删除用户【根据ID】")
public ***monResult<Integer> deleteUserById(@PathVariable("id") Long id) {
return userService.deleteUserById(id);
}
@PutMapping("/updateUser")
@Operation(summary = "编辑用户【根据ID】")
public ***monResult<Integer> updateUser(@RequestBody UserDO userDO) {
return userService.updateUser(userDO);
}
}
4、XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.coding.java.mapper.UserMapper">
<insert id="saveUser" parameterType="org.coding.java.domain.user.UserDO">
insert into user(name,age,phone,sex,email) value(#{name},#{age},#{phone},#{sex},#{email})
</insert>
<select id="selectList">
select id, name, age, phone, sex, email from user;
</select>
<delete id="deleteUserById">
delete from user where id = #{id}
</delete>
<update id="updateUser" parameterType="org.coding.java.domain.user.UserDO">
update user
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null and age != ''">
age = #{age},
</if>
<if test="phone != null and phone != ''">
phone = #{phone},
</if>
<if test="sex != null and sex != ''">
sex = #{sex},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
update_time = now()
</set>
where id = #{id}
</update>
<select id="selectPage">
select id, name, age, phone, sex, email from user where
<if test="item != null">
<if test="item.name != null and item.name != '' ">
name like '%' #{item.name} '%'
</if>
<if test="item.phone != null and item.phone != ''">
and phone = #{item.phone}
</if>
</if>
order by create_time desc
</select>
</mapper>
5、测试数据是否能走通