MyBatis_plus学习

首页 / 🍁编程类 / 正文

为什么要学习

我游玩b站的时候,发现很多项目现在都是springboot+mybatisplus做项目,已经很少用mybatis做项目了。
我学了两天mybatis-plus,把基本概念都过了一边。效果还行吧。

感受吧

学了俩天,效果感觉是可以的,plus版确实比原先的增强多了。简单的增删改查都不用去写mapper文件的sql了,plus版已经在底层写好了,只需要把泛型填写好。就欧克了

测试工具

1、我用的是idea工具
2、语言使用的,springboot+mybatis-plus
3、使用maven工具来构建jar包

声明

1、这篇文章不介绍与代码无关的东西。如果有需要了解的去mybatis——plus官网了解。
2、这篇文章可能还有一些小的问题,如果遇见或者测试的时候,碰见了请在下方留言。

测试

快速入门

步骤


1、创建数据库 mybatis_plus
2、创建user表

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

3、编写项目,初始化项目(用springboot初始化项目)
4、导入依赖

<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus 是自己开发,并非官方的! -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>

说明:我们使用 mybatis-plus 可以节省我们大量的代码,尽量不要同时导入 mybatis 和 mybatisplus!版本的差异!
5、连接数据库,这里的配置文件就写入springboot项目的配置文件里面即可。

#mysql 5 驱动不同 com.mysql.jdbc.Driver
#mysql 8 驱动不同com.mysql.cj.jdbc.Driver、需要增加时区的配置
serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?
useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

6、使用mybatis——plus之后

  • pojo

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
    }
  • mapper接口

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.kuang.pojo.User;
    import org.springframework.stereotype.Repository;
    // 在对应的Mapper上面继承基本的类 BaseMapper
    @Repository // 代表持久层
    //@Mapper也可以使用这个
    public interface UserMapper extends BaseMapper<User> {
    // 所有的CRUD操作都已经编写完成了
    // 你不需要像以前的配置一大堆文件了!
    }
  • 在主启动类上面去扫描我们的mapper包下的所有的接口

    @SpringBootApplication
    @MapperScan("com.xiaonan.mybatisplus.mapper")
    public class MybatisPlusApplication {
    
      public static void main(String[] args) {
          SpringApplication.run(MybatisPlusApplication.class, args);
      }
    
    }

    说明:主要是使用@MapperScan("com.xiaonan.mybatisplus.mapper")

  • 测试类中测试

    @SpringBootTest
    class MybatisPlusApplicationTests {
    // 继承了BaseMapper,所有的方法都来自己父类
    // 我们也可以编写自己的扩展方法!
    @Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
    // 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
    // 查询全部用户
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
    }
    }

7、结果
启动那个测试类,可以发现运行结果显示出来了全部数据。

思考问题?


1、sql谁帮我们写的?Mybatis-plus写好了!
2、方法哪里来的?Mybatis-plus写好了!

配置日志

细节


1、把下面配置文件的代码,直接贴在刚刚springboot配置文件里面。
2、配置好之后,在运行的时候,就清晰可见的sql了。

我们所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!

# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

自动填充

数据库方面,可自行的百度,这里只说代码方面
1、在实体类字段属性上面需增加注解

// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

2、编写处理器来处理这个注解即可

@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
// setFieldValByName(String fieldName, Object fieldVal, MetaObject
metaObject
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}

3、测试插入
4、测试更新

查询操作

// 测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 测试批量查询!
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按条件查询之一使用map操作
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
// 自定义要查询
map.put("name","小南");
map.put("age",3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

分页查询

如何使用


1、配置拦截器组件即可

@Configuration
public class MyBatisPlusConfig {

    // 分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

2、直接使用page对象即可!

// 测试分页查询
@Test
public void testPage(){
// 参数一:当前页
// 参数二:页面大小
// 使用了分页插件之后,所有的分页操作也变得简单的!
Page<User> page = new Page<>(2,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}

删除操作

// 测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1240620674645544965L);
}
// 通过id批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通过map删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","小南");
userMapper.deleteByMap(map);
}

条件构造器

Test
void contextLoads() {
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println); // 和我们刚才学习
的map对比一下
}
Test
void test2(){
// 查询名字狂神说
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","狂神说");
User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List
或者 Map
System.out.println(user);
}
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}
// 模糊查询
@Test
void test4(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
// 模糊查询
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
//测试六
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通过id进行排序
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}

结尾

我的gitee地址: https://gitee.com/nzy5201314/mybatis_plus
gitee里面也有一份pdf笔记!!!!

文章全部是本人原创,请勿转发,谢谢配合,版权所有-南香香-你会喜欢我吗

评论区
头像
    头像
    wu先生
      

    不明觉历啊。

      头像
      南香香
        
      @wu先生

      啥意思