- 添加依赖
<dependency> <groupId>com.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>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
-
配置属性信息
spring: datasource: driver-class-name: com.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 com.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.CommonResult; 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 CommonResult<Integer> saveUser(@RequestBody UserDO userDO) { return userService.saveUser(userDO); } @DeleteMapping("/deleteUser/{id}") @Operation(summary = "根据ID删除用户") public CommonResult<Integer> deleteUser(@PathVariable("id") Long id) { return userService.deleteUserById(id); } @GetMapping("/selectList") @Operation(summary = "查询用户信息") public CommonResult<List<UserDO>> selectList() { return userService.selectList(); } @PostMapping("/selectPage") @Operation(summary = "分页查询用户信息") public CommonResult<IPage<UserDO>> selectPage(@RequestBody PageQueryVO queryVO) { return userService.selectPage(queryVO); } @PutMapping("/updateUser") @Operation(summary = "更新用户信息") public CommonResult<Integer> updateUser(@RequestBody UserDO userDO) { return userService.updateUser(userDO); } }
package org.coding.java.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import jakarta.annotation.Resource; import org.coding.java.api.CommonResult; 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 CommonResult<Integer> saveUser(UserDO userDO) { return CommonResult.ok(ResponseMessage.MessageCode.SAVE_SUCCESS.code(), ResponseMessage.MessageCode.SAVE_SUCCESS.message(), userMapper.insert(userDO)); } @Override public CommonResult<Integer> deleteUserById(Long id) { int count = userMapper.deleteById(id); if (count > 0) { return CommonResult.ok(ResponseMessage.MessageCode.DELETE_SUCCESS.code(), ResponseMessage.MessageCode.DELETE_SUCCESS.message(), count); } return CommonResult.failed(ResponseMessage.MessageCode.DELETE_FAILED.code(), ResponseMessage.MessageCode.DELETE_FAILED.message(), count); } @Override public CommonResult<List<UserDO>> selectList() { if (getUserList().size() > 0) { return CommonResult.ok(ResponseMessage.MessageCode.SELECT_SUCCESS.code(), ResponseMessage.MessageCode.SELECT_SUCCESS.message(), getUserList()); } return CommonResult.failed(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), Collections.emptyList()); } @Override public CommonResult<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 CommonResult.ok(ResponseMessage.MessageCode.SELECT_SUCCESS.code(), ResponseMessage.MessageCode.SELECT_SUCCESS.message(), pageList); } else if (pageList.getRecords().size() == 0) { return CommonResult.failed(ResponseMessage.MessageCode.SELECT_NON_CONFORMANCE.code(), ResponseMessage.MessageCode.SELECT_NON_CONFORMANCE.message(), pageList); } return CommonResult.failed(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), pageList); } @Override public CommonResult<Integer> updateUser(UserDO userDO) { int update = userMapper.updateById(userDO); if (update > 0) { return CommonResult.ok(ResponseMessage.MessageCode.UPDATE_SUCCESS.code(), ResponseMessage.MessageCode.UPDATE_SUCCESS.message(), update); } return CommonResult.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 com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; import com.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 com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.time.LocalDateTime; /** * @Description: mybatis自动填充功能 */ @Component 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>com.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>com.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: com.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_cn
logging:
level:
org.coding.java.mapper: debug
3、编写测试代码
package org.coding.java.service.impl;
import com.github.pagehelper.IPage;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.coding.java.api.CommonResult;
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 CommonResult<Integer> saveUser(UserDO userDO) {
return CommonResult.ok(ResponseMessage.MessageCode.SAVE_SUCCESS.code(), ResponseMessage.MessageCode.SAVE_SUCCESS.message(), userMapper.saveUser(userDO));
}
@Override
public CommonResult<List<UserDO>> selectList() {
List<UserDO> list = userMapper.selectList();
if (list.size() > 0) {
return CommonResult.ok(ResponseMessage.MessageCode.SELECT_SUCCESS.code(), ResponseMessage.MessageCode.SELECT_SUCCESS.message(), list);
}
return CommonResult.ok(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), list);
}
@Override
public CommonResult<Integer> deleteUserById(Long id) {
Integer count = userMapper.deleteUserById(id);
if (count > 0) {
return CommonResult.ok(ResponseMessage.MessageCode.DELETE_SUCCESS.code(), ResponseMessage.MessageCode.DELETE_SUCCESS.message(), count);
}
return CommonResult.ok(ResponseMessage.MessageCode.DELETE_FAILED.code(), ResponseMessage.MessageCode.DELETE_FAILED.message(), count);
}
@Override
public CommonResult<Integer> updateUser(UserDO userDO) {
Integer count = userMapper.updateUser(userDO);
if (count > 0) {
return CommonResult.ok(ResponseMessage.MessageCode.UPDATE_SUCCESS.code(), ResponseMessage.MessageCode.UPDATE_SUCCESS.message(), count);
}
return CommonResult.ok(ResponseMessage.MessageCode.UPDATE_FAILED.code(), ResponseMessage.MessageCode.UPDATE_FAILED.message(), count);
}
@Override
public CommonResult<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 CommonResult.ok(ResponseMessage.MessageCode.SELECT_SUCCESS.code(), ResponseMessage.MessageCode.SELECT_SUCCESS.message(), pageInfo);
}
return CommonResult.ok(ResponseMessage.MessageCode.SELECT_FAILED.code(), ResponseMessage.MessageCode.SELECT_FAILED.message(), pageInfo);
}
}
package org.coding.java.controller;
import com.github.pagehelper.IPage;
import com.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.CommonResult;
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 CommonResult<Integer> saveUser(@RequestBody UserDO userDO) {
return userService.saveUser(userDO);
}
@GetMapping("/selectList")
@Operation(summary = "查询用户【不分页】")
public CommonResult<List<UserDO>> selectList() {
return userService.selectList();
}
@PostMapping("/selectPage")
@Operation(summary = "查询用户【分页】")
public CommonResult<PageInfo> selectPage(@RequestBody QueryPageVO pageVO) {
return userService.selectPage(pageVO);
}
@DeleteMapping("/deleteUserById/{id}")
@Operation(summary = "删除用户【根据ID】")
public CommonResult<Integer> deleteUserById(@PathVariable("id") Long id) {
return userService.deleteUserById(id);
}
@PutMapping("/updateUser")
@Operation(summary = "编辑用户【根据ID】")
public CommonResult<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、测试数据是否能走通
文章来源:https://www.toymoban.com/news/detail-838753.html
文章来源地址https://www.toymoban.com/news/detail-838753.html
到了这里,关于spring boot3整合mybatis-plus的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!