柚子快報邀請碼778899分享:MyBatis 復(fù)習(xí)文檔
柚子快報邀請碼778899分享:MyBatis 復(fù)習(xí)文檔
MyBatis 復(fù)習(xí)文檔:結(jié)合自定義擴展(假設(shè)為MyBatis-Flex)
引言 MyBatis 是一個優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis-Flex(假設(shè)的擴展)可能提供了額外的功能,如更便捷的CRUD操作、分頁插件、條件構(gòu)造器等,但本文檔將重點放在MyBatis的核心概念上,并假設(shè)MyBatis-Flex提供了類似MyBatis Plus的增強功能。
1.1數(shù)據(jù)庫搭建 mysql> CREATE TABLE IF NOT EXISTS tb_userinfo ( id INT(9) UNSIGNED NOT NULL AUTO_INCREMENT, cat_name VARCHAR(20) NOT NULL COMMENT ‘類別名稱’, parent_id INT(11) COMMENT ‘父級ID’, show_in_nav TINYINT(1) COMMENT ‘是否導(dǎo)航顯示’, sort_order SMALLINT(6) COMMENT ‘排序’, create_time DATETIME NOT NULL, update_time DATETIME NOT NULL, deleted INT(1) NOT NULL DEFAULT 0 COMMENT ‘邏輯刪除’, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=‘分類表’; 1.2數(shù)據(jù)庫表實現(xiàn) INSERT INTO tb_userinfo (id, cat_name, parent_id, show_in_nav, sort_order, create_time, update_time, deleted) VALUES (1, ‘前端’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (2, ‘Java’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (3, ‘Python’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (4, ‘人工智能’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (5, ‘AIGC’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (6, ‘算法’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (7, ‘移動開發(fā)’, 50, TRUE, NULL, ‘2023-07-04 17:01:00’, ‘2023-07-04 17:01:00’, FALSE), (8, ‘HarmonyOS’, 50, TRUE, NULL, ‘2023-07-04 17:02:00’, ‘2023-07-04 17:02:00’, FALSE), (9, ‘推薦’, 50, TRUE, NULL, ‘2023-07-04 17:02:00’, ‘2023-07-04 17:02:00’, FALSE), (10, ‘關(guān)注’, 50, TRUE, NULL, ‘2023-07-04 17:02:00’, ‘2023-07-04 17:02:00’, FALSE), (11, ‘運維’, 50, TRUE, NULL, ‘2023-07-04 17:02:00’, ‘2023-07-04 17:02:00’, FALSE);
環(huán)境搭建 2.1 依賴配置 在 Maven 項目中,首先需要在 pom.xml 文件中添加 MyBatis 和數(shù)據(jù)庫驅(qū)動的依賴。如果 MyBatis-Flex 是一個 Maven 依賴,也需要添加它。 org.springframework.boot spring-boot-starter-web com.mybatis-flex mybatis-flex-spring-boot-starter 1.8.1 com.mybatis-flex mybatis-flex-processor 1.8.1 provided com.alibaba druid-spring-boot-starter 1.2.6 mysql mysql-connector-java runtime org.projectlombok lombok org.springframework.boot spring-boot-starter-test test 2.2 MyBatis 配置 在 src/main/resources 目錄下創(chuàng)建 MyBatis 的配置文件yml,并配置數(shù)據(jù)源、事務(wù)管理器以及映射文件的位置。 spring: datasource: username: root password: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 druid: initial-size: 5 min-idle: 5 max-active: 20 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 100000 max-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: true aop-patterns: com.example.demo.* stat-view-servlet: enabled: true login-username: root login-password: 123456 web-stat-filter: enabled: true url-pattern: /* exclusions: ‘.js,.gif,.jpg,.png,.css,.ico,/druid/*’ filters: stat,wall filter: stat: slow-sql-millis: 1000 log-slow-sql: true enabled: true wall enabled: true config: drop-table-allow: false Mapper 接口 3.1 Mapper 接口 定義一個 Mapper 接口,用于聲明數(shù)據(jù)庫操作方法。 package com.example.spring1.demos.web.mapper;
import com.example.spring1.demos.web.pojo.ArticleCat; import com.mybatisflex.core.BaseMapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select;
import java.util.Date; import java.util.List; @Mapper public interface ArticleCatMapper extends BaseMapper {
// 通過ID查詢課程信息
@Select("SELECT * FROM tb_userinfo WHERE id = #{id}")
ArticleCat selectCourseById(@Param("id") Integer id);
@Select("SELECT create_time FROM tb_userinfo WHERE cat_name = #{cat_name}")
Date selectCourseCreatedAtByName(@Param("cat_name") String name);
} 3.2servlet層 package com.example.spring1.demos.web.Service;
import com.example.spring1.demos.web.mapper.ArticleCatMapper; import com.example.spring1.demos.web.pojo.ArticleCat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import java.util.Date; import java.util.List;
@Service public class ArticleCatService {
private ArticleCatMapper articleCatMapper;
@Autowired
public ArticleCatService(ArticleCatMapper articleCatMapper) {
this.articleCatMapper = articleCatMapper;
}
public ArticleCat getCourseById(Integer id) {
return articleCatMapper.selectCourseById(id);
}
public Date getCourseCreatedAtByName(String name) {
return articleCatMapper.selectCourseCreatedAtByName(name);
}
} 3.3控制層 package com.example.spring1.demos.web.Controller;
import com.example.spring1.demos.web.Service.ArticleCatService; import com.example.spring1.demos.web.pojo.ArticleCat;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import java.util.Date; import java.util.List;
@RestController @RequestMapping(“/api/articleCats”) public class ArticleCatController {
private ArticleCatService articleCatService;
@Autowired
public ArticleCatController(ArticleCatService courseService) {
this.articleCatService = courseService;
}
@GetMapping("/{id}")
public ResponseEntity
ArticleCat course = articleCatService.getCourseById(id);
return ResponseEntity.ok(course);
}
@GetMapping("/name/{name}")
public ResponseEntity
Date createdAt = articleCatService.getCourseCreatedAtByName(name);
return ResponseEntity.ok(createdAt);
}
} 3.4實體類 package com.example.spring1.demos.web.pojo;
import com.mybatisflex.annotation.Column; import com.mybatisflex.annotation.Id; import com.mybatisflex.annotation.KeyType; import com.mybatisflex.annotation.Table; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank; import java.io.Serializable; import java.util.Date;
@Data @Builder @NoArgsConstructor @AllArgsConstructor @ApiModel(“文章分類”) @Table(value = “article_cat”) public class ArticleCat implements Serializable { @Id(keyType = KeyType.Auto) @ApiModelProperty(“編號”) private Integer id;
@ApiModelProperty("分類")
@NotBlank(message = "分類不能為空")
private String cat_name;
@ApiModelProperty("父編號")
private Integer parentId;
@ApiModelProperty("排序")
private Integer sortOrder;
@ApiModelProperty("更新時間")
@Column(onInsertValue = "now()", onUpdateValue = "now()")
private Date updateTime;
@ApiModelProperty("創(chuàng)建時間")
@Column(onInsertValue = "now()")
private Date createTime;
@ApiModelProperty("模擬刪除標記")
private Integer deleted;
@ApiModelProperty("顯示在導(dǎo)航")
private ArticleCat show;
} 實現(xiàn)功能一截圖:
通過查詢課程名字來查詢課程創(chuàng)建時間 功能二截圖:
通過id來查詢課程名稱
柚子快報邀請碼778899分享:MyBatis 復(fù)習(xí)文檔
好文閱讀
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。