目录
一、背景
二、配置
1、pom文件配置
2、yml文件配置
3、SQL准备
三、具体代码(增删改查)
四、Wrapper中的QueryWrapper常用ge,gt,lt,le等具体含义
五、参考文献
一、背景
1.1 MyBatis-Plus 是由一个叫苞米豆的一个组织来开发的,组织负责人叫青苗,目前组织中大概有31人。MyBatis-Plus( https://mybatis.plus/)简称 MP是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。MyBatis-Plus 可以不需要写SQL语句就能快速完成单表的操作,MyBatis-Plus的愿景就是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
1.2 代码地址:
GitHub(https://github.com/baomidou/mybatis-plus)
码云(https://gitee.com/organizations/baomidou/)
本文主要以贴代码为主,实战为王。
二、配置
1、pom文件配置
<properties>
<java.version>1.8</java.version>
<mybatisplus.version>3.3.1</mybatisplus.version>
</properties>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatisplus.version}</version>
</dependency>
2、yml文件配置
#mybatis配置
mybatis-plus:
# 映射文件的位置
mapper-locations: classpath:mapper/*.xml
global-config:
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
#字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
field-strategy: NOT_NULL
#驼峰下划线转换
column-underline: true
logic-delete-value: -1
logic-not-delete-value: 0
banner: false
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
# 配置包别名
type-aliases-package: com.snowriver.it.springdemo.entity
3、SQL准备
CREATE TABLE `t_snow_operate_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`batch_no` varchar(32) DEFAULT NULL COMMENT '批次号',
`operator` varchar(255) NOT NULL DEFAULT '' COMMENT '操作人',
`operate_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
`operate_type` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '操作类型 1-导入 2-修改',
`operate_detail` varchar(255) NOT NULL DEFAULT '' COMMENT '操作明细(导入-附件名称 修改-报单id)',
`attachment_url` varchar(255) NOT NULL DEFAULT '' COMMENT '附件地址(操作类型为修改 该字段为空)',
`upload_status` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '上传状态 0-上传失败 1-上传成功 2-处理中',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2245 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='操作日志记录表';
三、具体代码(增删改查)
controller类:
@Slf4j
@RestController
@RequestMapping("/operate")
public class OperateLogController {
@Resource
private ISnowOperateLogService operateLogService;
@PostMapping("/insert")
public Result insert(@RequestBody OperateRecordReq request) {
SnowOperateLog operateLog = new SnowOperateLog();
operateLog.setOperator(request.getOperator());
operateLog.setOperateTime(request.getOperateTimeStart());
operateLog.setOperateType(Integer.valueOf(request.getOperateType()));
operateLogService.save(operateLog);
return Result.success();
}
@PostMapping("/insert-batch")
public Result insertBatch(@RequestBody OperateRecordReq request) {
LocalDateTime dateTime = LocalDateTime.now();
List<SnowOperateLog> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
SnowOperateLog operateLog = new SnowOperateLog();
operateLog.setBatchNo(String.valueOf(System.currentTimeMillis()));
operateLog.setOperator("liudehua" + i);
operateLog.setOperateType(1);
operateLog.setOperateTime(dateTime);
list.add(operateLog);
}
operateLogService.saveBatch(list);
return Result.success();
}
@GetMapping("/delete")
public Result<List<SnowOperateLog>> deleteById(@RequestParam(value = "id") String id) {
operateLogService.deleteById(id);
return Result.success();
}
@PostMapping("/update-by-name")
public Result updateByOperator(@RequestBody OperateRecordReq request) {
operateLogService.updateByOperator(request.getOperator());
return Result.success();
}
@PostMapping("/queryList")
public Result<PageDto<SnowOperateLog>> queryList(@RequestBody OperateRecordReq request) {
return operateLogService.queryList(request);
}
@PostMapping("/query-by-name")
public Result<List<SnowOperateLog>> selectAllByOperator(@RequestBody OperateRecordReq request) {
List<SnowOperateLog> snowOperateLogs = operateLogService.selectAllByOperator(request.getOperator());
return Result.success(snowOperateLogs);
}
}
服务类:
public interface ISnowOperateLogService extends IService<SnowOperateLog> {
Result<PageDto<SnowOperateLog>> queryList(OperateRecordReq request);
List<SnowOperateLog> selectAllByOperator(String operator);
void updateByOperator(String operator);
void deleteById(String id);
}
实现类:
@Slf4j
@Service
public class SnowOperateLogServiceImpl extends ServiceImpl<SnowOperateLogMapper, SnowOperateLog> implements
ISnowOperateLogService {
@Resource
private SnowOperateLogMapper operateLogMapper;
// 注意:不配置MybatisPlusConfig分页不生效 TokenKind
@Override
public Result<PageDto<SnowOperateLog>> queryList(OperateRecordReq request) {
LambdaQueryWrapper<SnowOperateLog> wrapper = Wrappers.lambdaQuery(SnowOperateLog.class);
IPage<SnowOperateLog> page = new Page<>(request.getPageNum(),request.getPageSize());
wrapper
.eq(SnowOperateLog::getOperator,request.getOperator())
.eq(SnowOperateLog::getOperateType,request.getOperateType())
.ge(SnowOperateLog::getOperateTime,request.getOperateTimeStart())
.le(SnowOperateLog::getOperateTime,request.getOperateTimeEnd())
.orderByDesc(SnowOperateLog::getId);
IPage<SnowOperateLog> logIPage = operateLogMapper.selectPage(page,wrapper);
PageDto<SnowOperateLog> result = new PageDto<>(logIPage.getTotal(), logIPage.getPages()
, logIPage.getCurrent(), logIPage.getSize()
, logIPage.getRecords());
return Result.success(result);
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<SnowOperateLog> selectAllByOperator(String operator) {
// // 自定义方法和SQL实现功能
// List<SnowOperateLog> snowOperateLogs = operateLogMapper.selectAllByOperator(operator);
LambdaQueryWrapper<SnowOperateLog> queryWrapper = Wrappers.lambdaQuery(SnowOperateLog.class)
.eq(SnowOperateLog::getOperator, operator);
List<SnowOperateLog> snowOperateLogs = operateLogMapper.selectList(queryWrapper);
// 批量打印日志
snowOperateLogs.forEach(System.out::println);
return snowOperateLogs;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateByOperator(String operator) {
LambdaUpdateWrapper<SnowOperateLog> wrapper = Wrappers.lambdaUpdate(SnowOperateLog.class)
.eq(SnowOperateLog::getOperator, "张三")
.set(SnowOperateLog::getOperator, "张三疯======");
super.update(wrapper);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteById(String id) {
LambdaQueryWrapper<SnowOperateLog> wrapper = Wrappers.lambdaQuery(SnowOperateLog.class)
.eq(SnowOperateLog::getId, id);
super.remove(wrapper);
}
}
mapper类
@Mapper
public interface SnowOperateLogMapper extends BaseMapper<SnowOperateLog> {
List<SnowOperateLog> selectAllByOperator(@Param("operator") String operator);
}
mapper.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="com.snowriver.it.springdemo.mapper.SnowOperateLogMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.snowriver.it.springdemo.entity.SnowOperateLog">
<id column="id" property="id" />
<result column="batch_no" property="batchNo" />
<result column="operator" property="operator" />
<result column="operate_time" property="operateTime" />
<result column="operate_type" property="operateType" />
<result column="operate_detail" property="operateDetail" />
<result column="attachment_url" property="attachmentUrl" />
<result column="upload_status" property="uploadStatus" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, batch_no, operator, operate_time, operate_type, operate_detail, attachment_url, upload_status
</sql>
<select id="selectAllByOperator" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_snow_operate_log
where operator = #{operator, jdbcType=VARCHAR}
</select>
</mapper>
配置类:MybatisPlusConfig
备注:如果没有该类,分页查询不生效
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
实体类
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_snow_operate_log")
public class SnowOperateLog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 批次号
*/
private String batchNo;
/**
* 操作人
*/
private String operator;
/**
* 操作时间
*/
private LocalDateTime operateTime;
/**
* 操作类型 1-导入 2-修改
*/
private Integer operateType;
/**
* 操作明细(导入-附件名称 修改-报单id)
*/
private String operateDetail;
/**
* 附件地址(操作类型为修改 该字段为空)
*/
private String attachmentUrl;
/**
* 上传状态 0-上传失败 1-上传成功 2-处理中
*/
private Integer uploadStatus;
}
问:SnowOperateLogServiceImpl继承ServiceImpl就可以获得service层的方法,为什么还需要实现ISnowOperateLogService接口?
答:实现 ISnowOperateLogService 接口能够更方便地对业务进行扩展,一些复杂场景下的数据处理,MyBatisPlus 提供的 Service 方法可能无法处理,此时我们就需要自己编写代码,这时候只需在 ISnowOperateLogService 中定义自己的方法,并在 SnowOperateLogServiceImpl 中实现即可。具体见这行代码(SnowOperateLogServiceImpl类):
List<SnowOperateLog> snowOperateLogs = operateLogMapper.selectAllByOperator(operator);
四、Wrapper中的QueryWrapper常用ge,gt,lt,le等具体含义
这个自己看源码就行,具体的类在是com.baomidou.mybatisplus.core.conditions.interfaces.interface
方法名 | 方法描述 |
allEq | map 所有非空属性等于 = |
eq | 等于 = |
ne | 不等于 <> |
gt | 大于 > |
ge | 大于等于 >= |
lt | 小于 < |
le | 小于等于 <= |
between | ETWEEN 值1 AND 值2 |
notBetween | NOT BETWEEN 值1 AND 值2 |
like | LIKE '%值%' |
notLike | NOT LIKE '%值%' |
likeLeft | LIKE '%值' |
likeRight | LIKE '值%' |
五、参考文献
1、MyBatis-Plus 简介
https://blog.csdn.net/vbirdbest/article/details/108890279
2、Wrappers.<实体>lambdaQuery的使用
https://blog.csdn.net/huang6chen6/article/details/120548281