mybatis-plus入门

金歌  金牌会员 | 2022-11-21 15:39:41 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 916|帖子 916|积分 2748

1、快速开始

1.1、现有一张 User 表,其表结构如下

idnameageemali1Jone18test1@baomidou.com2Jack20test2@baomidou.com3Tom28test3@baomidou.com4Sandy21test4@baomidou.com5Billie24test5@baomidou.com

  • SQL语句
  1. DROP TABLE IF EXISTS user;
  2. CREATE TABLE `user` (
  3.   `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  4.   `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  5.   `age` int DEFAULT NULL COMMENT '年龄',
  6.   `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  7.   `is_deleted` int NOT NULL DEFAULT '0' COMMENT '逻辑删除',
  8.   PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
  10. DELETE FROM user;
  11. INSERT INTO user (id, name, age, email,is_deleted) VALUES
  12. (1, 'Jone', 18, 'test1@baomidou.com',0),
  13. (2, 'Jack', 20, 'test2@baomidou.com',0),
  14. (3, 'Tom', 28, 'test3@baomidou.com',0),
  15. (4, 'Sandy', 21, 'test4@baomidou.com',0),
  16. (5, 'Billie', 24, 'test5@baomidou.com',0);
复制代码
1.2、引入依赖


  • mybatis-plus-boot-starter
  1.        <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-web</artifactId>
  4.         </dependency>
  5.         <dependency>
  6.             <groupId>com.baomidou</groupId>
  7.             <artifactId>mybatis-plus-boot-starter</artifactId>
  8.             <version>3.5.2</version>
  9.         </dependency>
  10.         <dependency>
  11.             <groupId>mysql</groupId>
  12.             <artifactId>mysql-connector-java</artifactId>
  13.             <scope>runtime</scope>
  14.         </dependency>
  15.         <dependency>
  16.             <groupId>com.alibaba</groupId>
  17.             <artifactId>druid-spring-boot-starter</artifactId>
  18.             <version>1.2.11</version>
  19.         </dependency>
  20.         <dependency>
  21.             <groupId>org.springframework.boot</groupId>
  22.             <artifactId>spring-boot-starter-test</artifactId>
  23.             <scope>test</scope>
  24.         </dependency>
  25.         <dependency>
  26.             <groupId>junit</groupId>
  27.             <artifactId>junit</artifactId>
  28.             <scope>test</scope>
  29.         </dependency>
复制代码
1.3、配置数据库连接,开启控制台SQL语句输出
  1. spring:
  2.   datasource:
  3.     type: com.alibaba.druid.pool.DruidDataSource
  4.     driver-class-name: com.mysql.cj.jdbc.Driver
  5.     url: jdbc:mysql://114.67.111.175:3306/test
  6.     username: wq
  7.     password: 123456
  8. #开启控制台日志
  9. mybatis-plus:
  10.   configuration:
  11.     #控制台打印sql语句方便调试sql语句执行错误
  12.     log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  13.     #这个不在控制台打印查询结果,但是在log4j2中打印
  14.     #log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
复制代码

  • 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
  1. @SpringBootApplication
  2. @MapperScan("com.wanqi.mybatisplus.mapper")
  3. public class Application {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(Application.class, args);
  6.     }
  7. }
复制代码
1.4、编码


  • 实体类User
  1. package com.wanqi.mybatisplus.pojo;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. @TableName("user") //指定表名
  5. public class User {
  6.     //type = IdType.AUTO自增字段需要修改数据库主键为自增
  7.     //value指定对应主键字段名,type指定id生成策略(默认策略为雪花算法)
  8.     @TableId(value = "id", type = IdType.AUTO)
  9.     private Long id;
  10.     //value数据库字段值
  11.     @TableField(value = "name")
  12.     private String name;
  13.     private Integer age;
  14.     private String email;
  15.     private Integer isDeleted;
  16.     public User(Long id, String name, Integer age, String email) {
  17.         this.id = id;
  18.         this.name = name;
  19.         this.age = age;
  20.         this.email = email;
  21.     }
  22.     public User(String name, Integer age, String email) {
  23.         this.name = name;
  24.         this.age = age;
  25.         this.email = email;
  26.     }
  27.     public User() {
  28.     }
  29.     public Long getId() {
  30.         return id;
  31.     }
  32.     public void setId(Long id) {
  33.         this.id = id;
  34.     }
  35.     public String getName() {
  36.         return name;
  37.     }
  38.     public void setName(String name) {
  39.         this.name = name;
  40.     }
  41.     public Integer getAge() {
  42.         return age;
  43.     }
  44.     public void setAge(Integer age) {
  45.         this.age = age;
  46.     }
  47.     public String getEmail() {
  48.         return email;
  49.     }
  50.     public void setEmail(String email) {
  51.         this.email = email;
  52.     }
  53.    public Integer getIsDeleted() {
  54.         return isDeleted;
  55.     }
  56.     public void setIsDeleted(Integer isDeleted) {
  57.         this.isDeleted = isDeleted;
  58.     }
  59.     @Override
  60.     public String toString() {
  61.         return "User{" +
  62.                 "id=" + id +
  63.                 ", name='" + name + '\'' +
  64.                 ", age=" + age +
  65.                 ", email='" + email + '\'' +
  66.                 ", isDeleted=" + isDeleted +
  67.                 '}';
  68.     }
  69. }
复制代码

  • 编写 Mapper 包下的 UserMapper接口
  1. import com.wanqi.mybatisplus.pojo.User;
  2. import org.springframework.stereotype.Repository;
  3. @Repository
  4. public interface UserMapper extends BaseMapper<User> {
  5. }
复制代码
1.5、测试使用
  1. package com.wanqi.mybatisplus;
  2. import com.wanqi.mybatisplus.mapper.UserMapper;
  3. import com.wanqi.mybatisplus.pojo.User;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import java.util.ArrayList;
  8. import java.util.Collection;
  9. import java.util.List;
  10. @SpringBootTest
  11. class MybatisPlusApplicationTests {
  12.     @Autowired
  13.     private UserMapper userMapper;
  14.     @Test
  15.     public void testSelect() {
  16.         System.out.println(("----- selectAll method test ------"));
  17.         userMapper.insert(new User( "古力娜扎", 18, "test1@baomidou.com"));
  18.         List<User> userList = userMapper.selectList(null);
  19.         userList.forEach(System.out::println);
  20.     }
  21. }
复制代码
2、批量操作

2.1、增加Service 层代码
  1. package com.wanqi.mybatisplus.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.wanqi.mybatisplus.pojo.User;
  4. /**
  5. * @Description TODO
  6. * @Version 1.0.0
  7. * @Date 2022/9/1
  8. * @Author wandaren
  9. */
  10. public interface UserService extends IService<User> {
  11. }
复制代码

  • 注意 UserServiceImpl 必须要继承 MP 框架中的 ServiceImpl,不然要重写很多方法。
  1. package com.wanqi.mybatisplus.service;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.wanqi.mybatisplus.mapper.UserMapper;
  4. import com.wanqi.mybatisplus.pojo.User;
  5. import org.springframework.stereotype.Service;
  6. /**
  7. * @Description TODO
  8. * @Version 1.0.0
  9. * @Date 2022/9/1
  10. * @Author wandaren
  11. */
  12. @Service
  13. public class UserServiceImpl extends ServiceImpl<UserMapper, User>
  14.     implements UserService{
  15. }
复制代码
2.2、测试使用
  1. package com.wanqi.mybatisplus;
  2. import com.wanqi.mybatisplus.mapper.UserMapper;
  3. import com.wanqi.mybatisplus.pojo.User;
  4. import com.wanqi.mybatisplus.service.UserServiceImpl;
  5. import org.junit.jupiter.api.Test;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import java.util.ArrayList;
  9. import java.util.Collection;
  10. import java.util.List;
  11. @SpringBootTest
  12. class MybatisPlusApplicationTests {
  13.     @Autowired
  14.     private UserServiceImpl userService;
  15.     @Test
  16.     void contextLoads() {
  17.         Collection<User> userList = new ArrayList<>();
  18.         userList.add(new User("hhh", 18, "test1@baomidou.com"));
  19.         userList.add(new User("sss", 18, "test1@baomidou.com"));
  20.         userList.add(new User("ddd", 18, "test1@baomidou.com"));
  21.         userService.saveBatch(userList);
  22.         System.out.println(userService.list());
  23.     }
  24. }
复制代码
3、Service CURD

3.1、save
  1. // 插入一条记录(选择字段,策略插入)
  2. boolean save(T entity);
  3. // 插入(批量)
  4. boolean saveBatch(Collection<T> entityList);
  5. // 插入(批量)
  6. boolean saveBatch(Collection<T> entityList, int batchSize);
复制代码

3.2、saveOrUpdate
  1. // TableId 注解存在更新记录,否插入一条记录
  2. boolean saveOrUpdate(T entity);
  3. // 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
  4. boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
  5. // 批量修改插入
  6. boolean saveOrUpdateBatch(Collection<T> entityList);
  7. // 批量修改插入
  8. boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
复制代码

3.3、remove

[code]// 根据 entity 条件,删除记录boolean remove(Wrapper queryWrapper);// 根据 ID 删除boolean removeById(Serializable id);// 根据 columnMap 条件,删除记录boolean removeByMap(Map columnMap);// 删除(根据ID 批量删除)boolean removeByIds(Collection

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

金歌

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表