• 【MyBatis-Plus】的基本使用(SpringBoot)


    1、什么是 MyBatis-Plus

    Mybatis-Plus:为简化开发而生

            MyBatis-Plus(简称 MP)是一个基于 MyBatis 的增强工具,它对 Mybatis 的基础功能进行了增强,但未做任何改变。使得我们可以可以在 Mybatis 开发的项目上直接进行升级为 Mybatis-plus,正如它对自己的定位,它能够帮助我们进一步简化开发过程,提高开发效率。

            Mybatis-Plus 其实可以看作是对 Mybatis 的再一次封装,升级之后,对于单 表的 CRUD 操作,调用 Mybatis-Plus 所提供的 API 就能够轻松实现,此外还提供了各种查询方式、分页等行为。最最重要的,开发人员还不用去编写 XML,这就大大降低了开发难度

    2、快速使用

    1、导入依赖

    1. <dependency>
    2. <groupId>mysqlgroupId>
    3. <artifactId>mysql-connector-javaartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>com.baomidougroupId>
    7. <artifactId>mybatis-plus-boot-starterartifactId>
    8. <version>3.4.3.4version>
    9. dependency>
    10. <dependency>
    11. <groupId>com.baomidougroupId>
    12. <artifactId>mybatis-plusartifactId>
    13. <version>3.5.1version>
    14. dependency>
    15. <dependency>
    16. <groupId>com.baomidougroupId>
    17. <artifactId>mybatis-plus-annotationartifactId>
    18. <version>3.5.1version>
    19. dependency>

    2、 配置数据库参数

    1. spring.datasource.password=*******
    2. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    3. spring.datasource.username=root
    4. spring.datasource.url=jdbc:mysql://localhost:3306/library?serverTimezone=UTC
    5. #mybatis的日志
    6. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    7. #全局设置主键生成策略
    8. mybatis-plus.global-config.db-config.id-type=auto

    3、建一个数据库表

    4、文件目录

    5、实体类

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Book {
    5. @TableId
    6. int bookId;
    7. String bookName;
    8. int bookCounts;
    9. String detail;
    10. @TableField(fill= FieldFill.INSERT)
    11. private Date createTime;
    12. @TableField(fill=FieldFill.INSERT_UPDATE)
    13. private Date updateTime;
    14. @Version
    15. @TableField(fill= FieldFill.INSERT)
    16. private Integer version;
    17. }

    6、做表映射

    1. @Repository
    2. public interface BookMapper extends BaseMapper {
    3. }

    7、 可以开始测试

     3、一般用法

    (1).查找和更新操作

    1. /**
    2. * 插入用户表一条数据
    3. */
    4. @Test
    5. public void testInsert(){
    6. Book b1=new Book();
    7. b1.setBookName("《xxxxxx》");
    8. b1.setBookCounts(299);
    9. b1.setDetail("学会使用常用的linux指令");
    10. int result=bookMapper.insert(b1);
    11. System.out.println(result);
    12. }
    13. /**
    14. * 根据多个id查询
    15. */
    16. @Test
    17. public void testSelectBatchIds(){
    18. List books=bookMapper.selectBatchIds(Arrays.asList(1,2,3));
    19. books.forEach(System.out::println);
    20. }
    21. /**
    22. * 简单的条件查询,通过map封装查询条件
    23. */
    24. @Test
    25. public void testSelectMap(){
    26. HashMap map=new HashMap<>();
    27. map.put("book_name","《爱迪生的伟大发明》");
    28. // map.put("detail","睡前小故事");
    29. List books=bookMapper.selectByMap(map);
    30. books.forEach(System.out::println);
    31. }
    32. /**
    33. * 通过id修改用户信息
    34. */
    35. @Test
    36. public void testUpdateById(){
    37. Book b=new Book();
    38. b.setBookId(15);
    39. b.setBookName("《Linux私房菜》");
    40. b.setDetail("好好学习指令 这是3.0版本");
    41. b.setBookCounts(100);
    42. int res=bookMapper.updateById(b);
    43. System.out.println(res);
    44. }

    (2) . 乐观锁使用

            1. 编写配置类,加入官方给的拦截器功能 ,分页也是这个 一同加上了,表中的version字段要记得写上。

    1. /**
    2. * 乐观锁插件
    3. * 分页插件
    4. */
    5. @Bean
    6. public MybatisPlusInterceptor mybatisPlusInterceptor() {
    7. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    8. //配置乐观锁
    9. interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    10. //配置分页
    11. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    12. return interceptor;
    13. }
    1. /**
    2. * 测试乐观锁插入
    3. */
    4. @Test
    5. public void testOptimisticLocker(){
    6. Book b1=new Book();
    7. b1.setBookName("《深技大入场券》");
    8. b1.setBookCounts(33);
    9. b1.setDetail("我来了,神技大");
    10. int result=bookMapper.insert(b1);
    11. System.out.println(result);
    12. }
    13. /**
    14. * 测试乐观锁更新
    15. */
    16. @Test
    17. public void testUpdateByIdOptimisticLocker(){
    18. //必须查询才能更新
    19. Book b=bookMapper.selectById(16);
    20. b.setBookId(16);
    21. b.setBookName("《深技大入场券》");
    22. b.setDetail("我来了,神技大 一定要上");
    23. b.setBookCounts(999);
    24. int res=bookMapper.updateById(b);
    25. System.out.println(res);
    26. }

    (3). 删除操作

    1. /**
    2. * 根据id删除
    3. */
    4. @Test
    5. public void testDeleteById(){
    6. int id=bookMapper.deleteById(17);
    7. System.out.println(id);
    8. }
    9. /**
    10. * 批量删除数据
    11. */
    12. @Test
    13. public void testDeleteBatchByIds(){
    14. int result=bookMapper.deleteBatchIds(Arrays.asList(18,19));
    15. System.out.println(result);
    16. }
    17. /**
    18. * 条件删除
    19. */
    20. @Test
    21. public void testDeleteByMap(){
    22. //DELETE FROM book WHERE book_counts = ?
    23. HashMap map=new HashMap<>();
    24. map.put("book_counts",299);
    25. int result=bookMapper.deleteByMap(map);
    26. }

    (4)分页查询

    1. /**
    2. * 分页查询
    3. */
    4. @Test
    5. public void testSelectPage(){
    6. //current 目前的
    7. Page page=new Page<>(1,5);
    8. bookMapper.selectPage(page, Wrappers.lambdaQuery().ge(Book::getBookId,2));
    9. List record=page.getRecords();
    10. record.forEach(System.out::println);
    11. //常用方法
    12. // boolean hasNext=page.hasNext();
    13. // boolean hasPrevious=page.hasPrevious();
    14. // System.out.println(hasNext+" "+hasPrevious);
    15. }

    4. 复杂查询

    Mybatis-Plus提供了两个常用类处理复杂查询操作,QueryWrapperUpdateWrapper

    1. /**
    2. * 复杂查询的
    3. * ge gt le lt isNull isNotNull的用法
    4. */
    5. @Test
    6. public void testQueryWrapper1(){
    7. QueryWrapper query=new QueryWrapper<>();
    8. //SELECT COUNT(*) AS total FROM book WHERE (book_counts >= ? AND book_name IS NOT NULL)
    9. query.ge("book_counts",60).isNotNull("book_name");
    10. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    11. // WHERE (book_counts >= ? AND book_name IS NOT NULL) LIMIT ?
    12. Page page=new Page<>(1,5);
    13. bookMapper.selectPage(page,query);
    14. page.getRecords().forEach(System.out::println);
    15. }
    16. /**
    17. *
    18. * 复杂查询的
    19. * eq ne的用法
    20. */
    21. @Test
    22. public void testQueryWrapper2(){
    23. QueryWrapper queryWrapper=new QueryWrapper<>();
    24. queryWrapper.eq("book_id",13);
    25. Book book=bookMapper.selectOne(queryWrapper);
    26. System.out.println(book);
    27. }
    28. /**
    29. *
    30. * 复杂查询的
    31. * between notBetween的用法
    32. */
    33. @Test
    34. public void testQueryWrapper3(){
    35. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    36. // WHERE (book_counts BETWEEN ? AND ?)
    37. QueryWrapper queryWrapper=new QueryWrapper<>();
    38. queryWrapper.between("book_counts",20,60);
    39. List book=bookMapper.selectList(queryWrapper);
    40. book.forEach(System.out::println);
    41. }
    42. /**
    43. *
    44. * 复杂查询的
    45. * allEq的用法
    46. */
    47. @Test
    48. public void testQueryWrapper4(){
    49. HashMap map=new HashMap();
    50. map.put("book_name","《1003夜》");
    51. map.put("detail","睡前小故事");
    52. QueryWrapper queryWrapper=new QueryWrapper<>();
    53. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    54. // WHERE (detail = ? AND book_name = ?)
    55. queryWrapper.allEq(map);
    56. List l=bookMapper.selectList(queryWrapper);
    57. l.forEach(System.out::println);
    58. }
    59. /**
    60. *
    61. * 复杂查询的
    62. * like notLike likeLeft likeRight
    63. */
    64. @Test
    65. public void testQueryWrapper5(){
    66. QueryWrapper queryWrapper=new QueryWrapper<>();
    67. queryWrapper.like("book_name","ql")
    68. .notLike("book_name","no");
    69. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    70. // WHERE (book_name LIKE ? AND book_name NOT LIKE ?)
    71. List> list=bookMapper.selectMaps(queryWrapper);
    72. System.out.println(list);
    73. }
    74. /**
    75. *
    76. * 复杂查询的
    77. * in notIn inSql notInSql exist notExists
    78. */
    79. @Test
    80. public void testQueryWrapper6(){
    81. QueryWrapper queryWrapper=new QueryWrapper<>();
    82. queryWrapper.inSql("book_id","select book_id from Book where book_id<10");
    83. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    84. // WHERE (book_id IN (select book_id from Book where book_id<10))
    85. List bookIds=bookMapper.selectObjs(queryWrapper);
    86. System.out.println(bookIds);
    87. }
    88. /**
    89. *
    90. * 复杂查询的
    91. * or and
    92. */
    93. @Test
    94. public void testQueryWrapper7(){
    95. UpdateWrapper updateWrapper=new UpdateWrapper<>();
    96. Book book=new Book();
    97. book.setBookId(15);
    98. book.setBookName("《Linux私房菜》");
    99. book.setBookCounts(81);
    100. // UPDATE book SET book_name=?, book_counts=?, update_time=?
    101. // WHERE (book_name LIKE ? OR book_counts LIKE ?)
    102. updateWrapper.like("book_name","《Linux私房菜》").or().like("book_counts",15);
    103. int result=bookMapper.update(book,updateWrapper);
    104. System.out.println(result);
    105. }
    106. /**
    107. *
    108. * 复杂查询的
    109. * 嵌套or 嵌套and
    110. */
    111. @Test
    112. public void testQueryWrapper8(){
    113. UpdateWrapper updateWrapper=new UpdateWrapper<>();
    114. Book book=new Book();
    115. book.setBookId(13);
    116. book.setBookName("《Mysql高级进阶》");
    117. book.setBookCounts(88);
    118. //UPDATE book SET book_name=?, book_counts=?, update_time=?
    119. // WHERE (book_name LIKE ? OR (detail = ? AND book_counts <> ?))
    120. //使用了lambda表达式,or中的表达式后面的条件会加上括号
    121. updateWrapper.like("book_name","xxx")
    122. .or(i->i.eq("detail","xxxxxx").ne("book_counts",999));
    123. // UPDATE book SET book_name=?, book_counts=?, update_time=?
    124. // WHERE (book_name LIKE ? OR detail = ? AND book_counts <> ?)
    125. // updateWrapper.like("book_name","xxx")
    126. // .or().eq("detail","xxxxxx").ne("book_counts",999);
    127. int result=bookMapper.update(book,updateWrapper);
    128. System.out.println(result);
    129. }
    130. /**
    131. *
    132. * 复杂查询的
    133. * 9.orderBy orderByDesc orderByAsc
    134. */
    135. @Test
    136. public void testQueryWrapper9(){
    137. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    138. // ORDER BY book_id ASC
    139. // orderBy(执行条件,'是否正序',排序的列)
    140. QueryWrapper queryWrapper=new QueryWrapper<>();
    141. queryWrapper.orderBy(true,true,"book_id");
    142. List books=bookMapper.selectList(queryWrapper);
    143. System.out.println(books);
    144. }
    145. /**
    146. *
    147. * 复杂查询的
    148. * 10.last
    149. * 只能调用一次,多次调用以最后一次为准 有sql注入的风险
    150. */
    151. @Test
    152. public void testQueryWrapper10(){
    153. QueryWrapper queryWrapper=new QueryWrapper<>();
    154. //SELECT book_id,book_name,book_counts,detail,create_time,update_time,version FROM book
    155. // limit 1
    156. queryWrapper.last("limit 1");
    157. Book book=bookMapper.selectOne(queryWrapper);
    158. System.out.println(book);
    159. }
    160. /**
    161. *
    162. * 复杂查询的
    163. * 11. 指点呀查询的列
    164. */
    165. @Test
    166. public void testQueryWrapper11(){
    167. QueryWrapper queryWrapper=new QueryWrapper<>();
    168. //SELECT book_id,book_name FROM book
    169. queryWrapper.select("book_id","book_name");
    170. List list=bookMapper.selectList(queryWrapper);
    171. list.forEach(System.out::println);
    172. }
    173. /**
    174. *
    175. * 复杂查询的
    176. * 12. set setSql
    177. */
    178. @Test
    179. public void testQueryWrapper12(){
    180. UpdateWrapper updateWrapper=new UpdateWrapper<>();
    181. Book book=new Book();
    182. book.setDetail("xxxx");
    183. //UPDATE book SET book_counts=?, detail=?, update_time=?, book_name=?,book_counts=?
    184. // WHERE (book_name LIKE ? OR book_id BETWEEN ? AND ?)
    185. updateWrapper.like("book_name","《xxxxxxxxx》")
    186. .or()
    187. .between("book_id",1,20)
    188. .set("book_name","《Redis入门学习》")
    189. // .setSql("detail='学好努力做缓存'")
    190. .set("book_counts",50);
    191. int result=bookMapper.update(book,updateWrapper);
    192. System.out.println(result);
    193. System.out.println(book);
    194. }
    195. 相关阅读:
      Win11壁纸变黑怎么办?Win11壁纸变黑了的解决方法
      golang 必会之 pprof 监控系列(5) —— cpu 占用率 统计原理
      PostgreSQL 16数据库的yum、编译、docker三种方式安装——筑梦之路
      安卓应用的MD5、SHA1值和公钥可以这样知道
      Redis缓存以及存在的问题--缓存穿透、缓存雪崩、缓存击穿及解决方法
      XPath的使用
      网络分析笔记01:pcapng格式的整体解包
      istio系列:第四章-Ingress网关配置
      等保到底在“保”什么?
      关于promethus+grafana的监控exporter访问/为errorpage404(notfound)重写exporter
    196. 原文地址:https://blog.csdn.net/m0_56233309/article/details/126877683