本篇內容介紹了“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如何使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注創新互聯網站,小編將為大家輸出更多高質量的實用文章!
文章題目:Mybatis如何使用
文章源于:http://vcdvsql.cn/article14/pdisde.html
成都網站建設公司_創新互聯,為您提供網站營銷、定制開發、、網站維護、動態網站、關鍵詞優化
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯