您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“Mybatis如何使用”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
<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: #數(shù)據(jù)庫(kù)相關(guān)配置 db-config: #主鍵類(lèi)型 AUTO:"數(shù)據(jù)庫(kù)ID自增", INPUT:"用戶輸入ID", ID_WORKER:"全局唯一ID (數(shù)字類(lèi)型唯一ID)", UUID:"全局唯一ID UUID"; id-type: AUTO #字段策略 IGNORED:"忽略判斷",NOT_NULL:"非 NULL 判斷"),NOT_EMPTY:"非空判斷" field-strategy: NOT_NULL #駝峰下劃線轉(zhuǎn)換 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 '批次號(hào)', `operator` varchar(255) NOT NULL DEFAULT '' COMMENT '操作人', `operate_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作時(shí)間', `operate_type` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '操作類(lèi)型 1-導(dǎo)入 2-修改', `operate_detail` varchar(255) NOT NULL DEFAULT '' COMMENT '操作明細(xì)(導(dǎo)入-附件名稱(chēng) 修改-報(bào)單id)', `attachment_url` varchar(255) NOT NULL DEFAULT '' COMMENT '附件地址(操作類(lèi)型為修改 該字段為空)', `upload_status` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '上傳狀態(tài) 0-上傳失敗 1-上傳成功 2-處理中', PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2245 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='操作日志記錄表';
controller類(lèi):
@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); } }
服務(wù)類(lèi):
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); }
實(shí)現(xiàn)類(lèi):
@Slf4j @Service public class SnowOperateLogServiceImpl extends ServiceImpl<SnowOperateLogMapper, SnowOperateLog> implements ISnowOperateLogService { @Resource private SnowOperateLogMapper operateLogMapper; // 注意:不配置MybatisPlusConfig分頁(yè)不生效 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實(shí)現(xiàn)功能 // 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類(lèi)
@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"> <!-- 通用查詢映射結(jié)果 --> <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> <!-- 通用查詢結(jié)果列 --> <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>
配置類(lèi):MybatisPlusConfig
備注:如果沒(méi)有該類(lèi),分頁(yè)查詢不生效
@Configuration public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); } }
實(shí)體類(lèi)
@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; /** * 批次號(hào) */ private String batchNo; /** * 操作人 */ private String operator; /** * 操作時(shí)間 */ private LocalDateTime operateTime; /** * 操作類(lèi)型 1-導(dǎo)入 2-修改 */ private Integer operateType; /** * 操作明細(xì)(導(dǎo)入-附件名稱(chēng) 修改-報(bào)單id) */ private String operateDetail; /** * 附件地址(操作類(lèi)型為修改 該字段為空) */ private String attachmentUrl; /** * 上傳狀態(tài) 0-上傳失敗 1-上傳成功 2-處理中 */ private Integer uploadStatus; }
問(wèn):SnowOperateLogServiceImpl繼承ServiceImpl就可以獲得service層的方法,為什么還需要實(shí)現(xiàn)ISnowOperateLogService接口?
答:實(shí)現(xiàn) ISnowOperateLogService 接口能夠更方便地對(duì)業(yè)務(wù)進(jìn)行擴(kuò)展,一些復(fù)雜場(chǎng)景下的數(shù)據(jù)處理,MyBatisPlus 提供的 Service 方法可能無(wú)法處理,此時(shí)我們就需要自己編寫(xiě)代碼,這時(shí)候只需在 ISnowOperateLogService 中定義自己的方法,并在 SnowOperateLogServiceImpl 中實(shí)現(xiàn)即可。具體見(jiàn)這行代碼(SnowOperateLogServiceImpl類(lèi)):
List<SnowOperateLog> snowOperateLogs = operateLogMapper.selectAllByOperator(operator);
四、Wrapper中的QueryWrapper常用ge,gt,lt,le等具體含義
這個(gè)自己看源碼就行,具體的類(lèi)在是com.baomidou.mybatisplus.core.conditions.interfaces.interface
“Mybatis如何使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。