免费爱碰视频在线观看,九九精品国产屋,欧美亚洲尤物久久精品,1024在线观看视频亚洲

      學(xué)會(huì)了MybatisPlus,代碼開(kāi)發(fā)效率提高了10倍

      學(xué)會(huì)了MybatisPlus,代碼開(kāi)發(fā)效率提高了10倍

      1. Mybatis 存在的痛點(diǎn)

      我們知道 MyBatis 是一個(gè)基于 java 的持久層框架,它內(nèi)部封裝了 jdbc,極大提高了我們的開(kāi)發(fā)效率

      但是使用 Mybatis 開(kāi)發(fā)也有很多痛點(diǎn):

    1. 每個(gè) Dao 接口都需要自己定義一堆增刪改查方法。
    2. /** * @Desc: UserDao 接口 * @Author: 公眾號(hào):知否技術(shù) * @date: 下午7:43 2022/5/7 */public interface UserDao { // 獲取所有用戶信息 List getUserList(); // 根絕 id 獲取用戶信息 User getUserById(int id); // 新增用戶信息 boolean add(User user); // 更新用戶信息 boolean update(User user); // 刪除用戶信息 boolean delete(int id);}復(fù)制代碼

      2.每個(gè) Mapper 文件都需要寫(xiě)一堆基本的增刪改查語(yǔ)句。

      3.如果查詢的列表需要分頁(yè),我們還需要給查詢方法封裝成分頁(yè)對(duì)象。

      你可能會(huì)說(shuō):Mybatis 還能有痛點(diǎn)?用著多方便!

      對(duì)于小項(xiàng)目而言,用著確實(shí)還行。但是遇到大項(xiàng)目,光 Dao 接口都有幾百個(gè),如果還要手動(dòng)定義一堆增刪改查方法和 sql 語(yǔ)句,那也很浪費(fèi)時(shí)間。

      那有沒(méi)有這樣一個(gè)框架:

      1.封裝了 Mybatis,自帶 CRUD 方法,我們不需要自己定義 CRUD 方法。

      2.提供各種查詢方法,不需要在 mapper 文件中寫(xiě)一些基礎(chǔ)的 sql 語(yǔ)句。

      3.封裝了分頁(yè)功能,讓分頁(yè)查詢無(wú)比絲滑。

      有的,MybatisPlus 閃亮登場(chǎng)。

      2. 邂逅 MybatisPlus

      官網(wǎng):

      https://baomidou.com/復(fù)制代碼

      MybatisPlus 是在 Mybatis 原有功能的基礎(chǔ)上進(jìn)行了封裝。它不做改變,而是增強(qiáng)了 Mybatis 的功能。

      我們不用寫(xiě) mappe.xml ,直接調(diào)用它的 API 就能完成 CRUD 和各種查詢操作。

      而且它自帶分頁(yè)插件等一些高級(jí)功能,極大地提高了我們的開(kāi)發(fā)效率。

      3. 入門(mén)案例

      開(kāi)發(fā)環(huán)境:

      • 開(kāi)發(fā)工具:IDEA
      • 構(gòu)建工具:Maven
      • 數(shù)據(jù)庫(kù):MySQL
      • 項(xiàng)目框架:SpringBoot

      1.新建 SpringBoot 項(xiàng)目

      2.引入依賴

      com.baomidou mybatis-plus-boot-starter 3.4.0 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test復(fù)制代碼

      3.創(chuàng)建數(shù)據(jù)庫(kù)表

      user 表:

      CREATE TABLE `user` ( `id` bigint NOT NULL AUTO_INCREMENT COMMENT ‘id’, `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT ‘姓名’, `age` int DEFAULT NULL COMMENT ‘年齡’, PRIMARY KEY (`id`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=1508421137384648706 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;復(fù)制代碼

      4.實(shí)體類(lèi)

      public class User { @TableId(value = “id”, type = IdType.ASSIGN_ID) private Long id; private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}復(fù)制代碼

      5.修改 application.yml

      server: port: 8082 servlet: context-path: /mybatisplus_demo# 數(shù)據(jù)源配置spring: datasource: username: root password: 12345678 url: jdbc:mysql://localhost:3306/ssm?allowPublicKeyRetrieval=true&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver復(fù)制代碼

      6.新建 UserMapper 接口

      注:

      (1)因?yàn)?mybatis 規(guī)定:mapper.xml 文件的名字要和接口名字一樣,所以很多人習(xí)慣將 Dao 接口命名為 xxxMapper。

      (2)BaseMapper 是 MybatisPlus 內(nèi)置的接口,它包含基本的 CRUD 方法。

      7.啟動(dòng)類(lèi)添加 @MapperScan 注解

      8.測(cè)試

      @SpringBootTestpublic class MybatisPlusDemoApplicationTests { @Resource private UserMapper userMapper; @Test void testMybatisPlus() { for (int i = 18; i < 20; i++) { User user = new User("王小波" + i, i); userMapper.insert(user); } }}

      9.總結(jié)

      我們發(fā)現(xiàn)只要繼承 MybatisPlus 的BaseMapper,就能完成基本的增刪改查操作,非常方便。

      4. 基本增刪改查

      1.新增

      User user = new User(“王小波”, 19);userMapper.insert(user);復(fù)制代碼

      2.編輯

      根據(jù) id 更新數(shù)據(jù)

      int rows = userMapper.updateById(user);if(rows>0){ System.out.println(“更新成功”); }復(fù)制代碼

      3.刪除

      根據(jù)主鍵刪除信息

      userMapper.deleteById(“152635612”);復(fù)制代碼

      根據(jù) map 條件刪除信息

      Map param = new HashMap();param.put(“age”, 18);int rows = userMapper.deleteByMap(param);if (rows > 0) { System.out.println(“刪除成功!”);}復(fù)制代碼

      根據(jù) id 集合批量刪除

      List ids = Stream.of(110, 112, 113, 115).collect(Collectors.toList());int rows = userMapper.deleteBatchIds(ids);if (rows > 0) { System.out.println(“刪除成功!”);}復(fù)制代碼

      4.查詢

      根據(jù) id 查詢

      User user = userMapper.selectById(152382374);復(fù)制代碼

      根據(jù) map 條件查詢

      Map param = new HashMap();param.put(“age”, 18);List userList = userMapper.selectByMap(param);復(fù)制代碼

      根據(jù) id 集合批量查詢

      List ids = Stream.of(110, 112, 113, 115).collect(Collectors.toList());List userList = userMapper.selectBatchIds(ids);復(fù)制代碼

      5. 構(gòu)造器

      MybatisPlus 提供了查詢構(gòu)造器和更新構(gòu)造器用來(lái)生成帶有 where 條件的 sql 語(yǔ)句。

      (1)封裝查詢條件的構(gòu)造器:

      QueryWrapper復(fù)制代碼

      常用查詢條件:

      等于:eq

      QueryWrapper userWrapper = new QueryWrapper();// 查詢名字是張三的用戶userWrapper.eq(“name”,”張三”);List userList = userMapper.selectList(userWrapper);復(fù)制代碼

      不等于:ne

      QueryWrapper userWrapper = new QueryWrapper();userWrapper.ne(“name”,”張三”);// 查詢名字不是張三的用戶List userList = userMapper.selectList(userWrapper);復(fù)制代碼

      模糊查詢:like

      QueryWrapper userWrapper = new QueryWrapper();// 模糊查詢userWrapper.like(“name”,”張”);List userList = userMapper.selectList(userWrapper);復(fù)制代碼

      降序:orderByDesc

      QueryWrapper userWrapper = new QueryWrapper();// 模糊查詢并根據(jù) number 倒序userWrapper.like(“name”,”張”).orderByDesc(“number”);List userList = userMapper.selectList(userWrapper);復(fù)制代碼

      升序:orderByAsc

      QueryWrapper userWrapper = new QueryWrapper();// 模糊查詢并根據(jù) number 降序userWrapper.like(“name”,”張”).orderByAsc(“number”);List userList = userMapper.selectList(userWrapper);復(fù)制代碼

      其他常用的條件可以去官網(wǎng)查看相關(guān)文檔,這里不再過(guò)多贅述:

      https://baomidou.com/pages/10c804/#in復(fù)制代碼

      (2)封裝更新條件的構(gòu)造器:

      UpdateWrapper復(fù)制代碼

      UpdateWrapper 的 where 條件和 QueryWrapper 的一樣,只不過(guò)需要 set 值。

      UpdateWrapper userWrapper = new UpdateWrapper();userWrapper.set(“name”,”王小波”).set(“age”,22) .eq(“name”,”張三”);復(fù)制代碼

      6. 通用 Service

      MybatisPlus 中有一個(gè)通用的接口 Iservice 和實(shí)現(xiàn)類(lèi),封裝了常用的增刪改查等操作。

      1.新建 service 和 實(shí)現(xiàn)類(lèi)

      UserService

      /** * @Desc: * @Author: 公眾號(hào):知否技術(shù) * @date: 下午9:57 2022/5/11 */public interface UserService extends IService {}復(fù)制代碼

      UserServiceImpl

      /** * @Desc: * @Author: 公眾號(hào):知否技術(shù) * @date: 下午9:57 2022/5/11 */@Servicepublic class UserServiceImpl extends ServiceImpl implements UserService {}復(fù)制代碼

      2.測(cè)試

      我們發(fā)現(xiàn)該 IService 接口封裝了一些常用的方法,極大地提高了我們的開(kāi)發(fā)效率。

      7. 常用注解

      1.@TableId

      MybatisPlus 會(huì)默認(rèn)將實(shí)體類(lèi)中的 id 作為主鍵。

      @TableId 表示 id 的生成策略,常用的有兩種:

      (1) 基于數(shù)據(jù)庫(kù)的自增策略

      (2) 使用雪花算法策略隨機(jī)生成

      2.@TableName

      如果實(shí)體類(lèi)和數(shù)據(jù)庫(kù)的表名不一致,可以使用這個(gè)注解做映射

      例如:

      3.@TableField

      當(dāng)表屬性和實(shí)體類(lèi)中屬性名不一致時(shí),可以使用這個(gè)注解做映射:

      8. 分頁(yè)

      MybatisPlus 內(nèi)部封裝了分頁(yè)插件,只用簡(jiǎn)單配置一下就能實(shí)現(xiàn)分頁(yè)功能。

      1.配置類(lèi)

      /** * @Desc: * @Author: 公眾號(hào):知否技術(shù) * @date: 下午9:31 2022/5/11 */@Configuration@MapperScan(“com.zhifou.mapper”)public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }}復(fù)制代碼

      2.測(cè)試

      @Testvoid testMybatisPlus() { int current = 1; int size = 10; Page userPage = new Page(current, size); //獲取分頁(yè)數(shù)據(jù) List list = userPage.getRecords(); list.forEach(user->{ System.out.println(user); }); Page page = userMapper.selectPage(userPage, null); System.out.println(“當(dāng)前頁(yè):” + page.getCurrent()); System.out.println(“每頁(yè)條數(shù):” + page.getSize()); System.out.println(“總記錄數(shù):” + page.getTotal()); System.out.println(“總頁(yè)數(shù):” + page.getPages());}復(fù)制代碼

      9. 代碼生成器

      MybatisPlus 可以幫助我們自動(dòng)生成 controller、service、dao、model、mapper.xml 等文件,極大地提高了我們的開(kāi)發(fā)效率。

      1.引入依賴

      com.baomidou mybatis-plus-generator 3.5.1 org.freemarker freemarker復(fù)制代碼

      2.代碼生成器工具類(lèi)

      public class CodeGenerator {public static void main(String[] args) {// 連接數(shù)據(jù)庫(kù)FastAutoGenerator.create(“jdbc:mysql://localhost:3306/ssm?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC”, “root”, “123456”) .globalConfig(builder -> { builder.author(“知否技術(shù)”) // 設(shè)置作者 .fileOverride() // 覆蓋已生成文件 // 設(shè)置日期時(shí)間 .dateType(DateType.ONLY_DATE) .outputDir(“D:WorkSpaceideamybatisplus_demosrcmainjava”); // 指定輸出目錄 }) .packageConfig(builder -> { builder.parent(“com.zhifou”) // 設(shè)置父包名 .pathInfo(Collections.singletonMap(OutputFile.mapperXml, “D:WorkSpaceideamybatisplus_demosrcmainresourcesmapper”)); // 設(shè)置mapperXml生成路徑 }) .strategyConfig(builder -> { builder.addInclude(“t_user”) // 設(shè)置需要生成的表名 .addTablePrefix(“t_”); // 設(shè)置過(guò)濾表前 // 新增數(shù)據(jù),自動(dòng)為創(chuàng)建時(shí)間賦值 IFill createFill = new Column(“created_date”, FieldFill.INSERT); IFill updateFill = new Column(“updated_date”, FieldFill.UPDATE); builder.entityBuilder() // 設(shè)置id類(lèi)型 .idType(IdType.ASSIGN_ID) // 開(kāi)啟 Lombok .enableLombok() // 開(kāi)啟連續(xù)設(shè)置模式 .enableChainModel() // 駝峰命名模式 .naming(NamingStrategy.underline_to_camel) .columnNaming(NamingStrategy.underline_to_camel) // 自動(dòng)為創(chuàng)建時(shí)間、修改時(shí)間賦值 .addTableFills(createFill).addTableFills(updateFill) // 邏輯刪除字段 .logicDeleteColumnName(“is_deleted”); // Restful 風(fēng)格 builder.controllerBuilder().enableRestStyle(); // 去除 Service 前綴的 I builder.serviceBuilder().formatServiceFileName(“%sService”); // mapper 設(shè)置 builder.mapperBuilder() .enableBaseResultMap() .enableBaseColumnList(); }) // 固定 .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默認(rèn)的是Velocity引擎模板 .execute(); }}復(fù)制代碼

      關(guān)鍵點(diǎn):

      (1)配置數(shù)據(jù)庫(kù)連接信息。

      自動(dòng)生成代碼需要連接數(shù)據(jù)庫(kù)

      (2)指定輸出目錄,這里直接設(shè)置你項(xiàng)目的目錄,到時(shí)候不用賦值粘貼了。

      (3)設(shè)置父包名。

      (4)設(shè)置表名

      然后右鍵運(yùn)行,代碼就會(huì)自動(dòng)生成。

      10. application.yml 配置

      # MybatisPlusmybatis-plus: global-config: db-config: column-underline: true # 駝峰形式 logic-delete-field: isDeleted # 全局邏輯刪除的實(shí)體字段名 logic-delete-value: 1 # 邏輯已刪除值(默認(rèn)為 1) logic-not-delete-value: 0 # 邏輯未刪除值(默認(rèn)為 0) db-type: mysql id-type: assign_id # id策略 table-prefix: t_ # 配置表的默認(rèn)前綴 mapper-locations: classpath*:/mapper/**Mapper.xml # mapper 文件位置 type-aliases-package: com.zhifou.entity # 實(shí)體類(lèi)別名 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志:打印sql 語(yǔ)句復(fù)制代碼

      11. 完整代碼

      鏈接: https://pan.baidu.com/s/1nlRjKOWs3ON53Dh1XXLKGw 提取碼: 9un7 復(fù)制代碼

      12. 遇到的坑

      1.傳參為 0 時(shí),查詢語(yǔ)句失效。

      例如傳遞的 age 為 0,查詢就會(huì)失效

      select id,name,age,sex from user age = #{age} 復(fù)制代碼

      原因:判斷 int 是否為空只要 !=null 就行了,如果加上 type != ”,0 會(huì)被轉(zhuǎn)為 null。

      2.MybatisPlus 更新字段為 null 失敗

      解決辦法:

      @TableField(updateStrategy = FieldStrategy.IGNORED)private String name;復(fù)制代碼

      該注解會(huì)忽略為空的判斷,

      鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場(chǎng),版權(quán)歸原作者所有,如有侵權(quán)請(qǐng)聯(lián)系管理員(admin#wlmqw.com)刪除。
      用戶投稿
      上一篇 2022年6月21日 06:50
      下一篇 2022年6月21日 06:50

      相關(guān)推薦

      聯(lián)系我們

      聯(lián)系郵箱:admin#wlmqw.com
      工作時(shí)間:周一至周五,10:30-18:30,節(jié)假日休息