本篇内容介绍了“Mybatis如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
<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>
#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
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"); }
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
“Mybatis如何使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。