首页 > 其他分享 >MyBatisPlus

MyBatisPlus

时间:2023-01-11 23:33:30浏览次数:58  
标签:MyBatisPlus name private public mybatisPlusInterceptor user id

MyBatisPlus

导入坐标

SpringBoot并没有收录mybatisplus,所以需要自己导入坐标

<dependency>
        <groupId>com.baomidou</groupId>
         <artifactId>mybatis-plus-boot-starter</artifactId>
         <version>3.4.3</version>
</dependency>

# 数据源
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
</dependency>

配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.NonRegisteringDriver
    url: jdbc:mysql://127.0.0.1:3306/mybatisplus_db?serverTimezone=UTC
    username: root
    password: root
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private String password;
    private Integer age;
    private String tel;
}

mapper

继承mybatisplus的basemapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.freshman.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

测试功能

 @Autowired
    private UserMapper userMapper;

    @Test
    void testSelectAll() {
        List<User> userList = userMapper.selectList(null);
        System.out.println(userList);
    }

image-20230111134636538

以上就是mybatispuls一个入门案例


概述

mybatisplus是基于mybatis框架基础上开发的增强型工具,旨在简化开发、提高效率

官网: https://mybatis.plus/ https://mp.baomidou.com/

标准数据层CRUD功能

功能 MP接口
新增 int insert(T t)
删除 int deleteById(Serializable id)
修改 int updateById(T t)
根据id查询 T selectById(Serializable id)
查询全部 List selectList()
分页查询 IPage selectPage(IPage page)
按条件查询 IPage selectPage(Wrapper queryWrapper)

讲一下分页查询

  1. 配置分页查询拦截器

    @Configuration
    public class MpConfig {
    
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor(){
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return mybatisPlusInterceptor;
        }
    }
    
  2. 测试

     @Test
        void testPage(){
            // select * from user limit 1,2;
            IPage<User> userPage = new Page<>(1,2);
            userMapper.selectPage(userPage,null);
            System.out.println("当前页码值:" + userPage.getCurrent());
            System.out.println("每页显示数:" + userPage.getSize());
            System.out.println("一共多少页:" + userPage.getPages());
            System.out.println("一共多少条数据:" + userPage.getTotal());
            System.out.println("要查询到的数据:" + userPage.getRecords());
        }
    
    /**
    ==>  Preparing: SELECT id,name,password,age,tel FROM user LIMIT ?
    ==> Parameters: 2(Long)
    <==    Columns: id, name, password, age, tel
    <==        Row: 1, zhangsan, 123, 12, null
    <==        Row: 2, lisi, 123, 12, null
    <==        Total: 2
    */
    

    image-20230111141535054

    image-20230111142028194

条件查询:

  1. lambdaquerywrapper

    @Test
        void testSelect(){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            // SELECT id,name,password,age,tel FROM user WHERE (age > ?)
            wrapper.gt(User::getAge,11);
            List<User> users = userMapper.selectList(wrapper);
            System.out.println(users);
        }
    
    /**
    ==>  Preparing: SELECT id,name,password,age,tel FROM user WHERE (age > ?)
    ==> Parameters: 11(Integer)
    <==    Columns: id, name, password, age, tel
    <==        Row: 1, zhangsan, 123, 12, 123
    <==        Row: 2, lisi, 123, 12, 123
    <==        Row: 3, wangwu, 123, 12, 123
    <==      Total: 3
    */
    

    更多方法:https://mybatis.plus/guide/wrapper.html#abstractwrapper

  2. 字段映射和表名映射

    // 设计表的名称
    @TableName("tbl_user")
    public class User{
        private Long id;
        private String name;
        // 在数据表中为pwd,且查询时不参与查询 即 selct id name from user;没有pwd
        @TableField(value = "pwd",select = false)
        private String password;
        // 数据库中不存在这个字段
        @TableField(exist = false)
        private Integer online;
    }
    
  3. id生成策略

    AUTO(0) 使用数据库id自增策略控制id生成
    NONE(1) 不设置id生成策略
    INPUT(2) 用户手工输入id
    ASSIGN_ID(3) 雪花算法生成id(可兼容数值型和字符串型)
    ASSIGN_UUID(4) 以UUID生成算法作为id生成策略

    雪花算法

    image-20230111213702312

    public class User{
        @TableId(type = IdType.AuTo)
        private Long id;
    }
    
  4. 逻辑删除

    为数据设置是否可用状态字段,删除时设置状态字段为不可用状态,数据保留在数据库中

    // value 为 默认不删除的值  delval 为 默认删除的值
    @TableLogic(value = "0",delval = "1")
     private Integer deleted;
    
    ==>  Preparing: UPDATE user SET deleted=1 WHERE id=? AND deleted=0
    ==> Parameters: 1(Long)
    <==    Updates: 1
    

    image-20230111220258223

  5. 全局配置

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      global-config:
        db-config:
          id-type: assign_id
          logic-delete-field: deleted
          logic-delete-value: 1
          logic-not-delete-value: 0
    
  6. 乐观锁

    1. 配置拦截器

      @Configuration
      public class MpConfig {
          @Bean
          public MybatisPlusInterceptor mybatisPlusInterceptor(){
              // 1、定义拦截器
              MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
              // 2、添加分页拦截器
              mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
              // 3、添加乐观锁拦截器
              mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
              return mybatisPlusInterceptor;
          }
      }
      
    2. 设置version

      @Version
      private Integer version;
      
    3. 测试方法

       	@Test
          void testUpdate(){
              User user = new User();
              user.setId(3L);
              user.setName("ligeng");
              user.setVersion(1);
              userMapper.updateById(user);
          }
      
      
      /**
      ==>  Preparing: UPDATE user SET name=?, version=? WHERE id=? AND version=? AND deleted=0
      ==> Parameters: ligeng(String), 2(Integer), 3(Long), 1(Integer) 这里第二个参数为2,即执行了version = version + 1
      <==    Updates: 1
      */
      
  7. 代码生成器 (使用mybatisx插件生成即可)

标签:MyBatisPlus,name,private,public,mybatisPlusInterceptor,user,id
From: https://www.cnblogs.com/freshman-me/p/17045200.html

相关文章

  • 42、mybatisplus配置分页插件
    1、旧版分页插件配置方法(MybatisPlus3.4.0版本之前)@EnableTransactionManagement//开启事务@Configuration@MapperScan(basePackages={"com.zimug.**.mapper"})p......
  • 增强MybatisPlus拓展新功能 实战MybatisPlus大合集
    mybatis-plus-max简介MybatisPlusMax是MybatisPlus的增强包,秉承只拓展不修改的理念,对MybatisPlus做增强。正如MybatisPlus是对MyBatis的增强,MybatisPlusMax是对MybatisPl......
  • MybatisPlus 实现多表联合分页条件查询
    方式一:XML有点繁琐,不太想用mapper接口publicinterfaceRoomMapperextendsBaseMapper<Room>{List<RoomVO>getRoomPageList(Pagepage,@Param("roomPageReq......
  • Java开发学习(五十)----MyBatisPlus快速开发之代码生成器解析
    1、代码生成器原理分析造句:我们可以往空白内容进行填词造句,比如:在比如:观察我们之前写的代码,会发现其中也会有很多重复内容,比如:那我们就想,如果我想做一个Book模块......
  • mybatisplus简单了解
    mybatisplus是加强版mybatis,里面提供了更加简便强大的功能。springboot整合mybatisplus,这个mybatisplus的jar包需要手动添加,不在起步依赖里面。  然后整合完之后,再在......
  • mybatisPlus逻辑删除
    1.在逻辑删除字段上添加@TableLogic注解@ApiModelProperty(value="状态:0未删除,1已删除")@TableLogic(value="0",delval="1")privateIntegerisDeleted;......
  • MybatisPlus代码生成器配置(处理blob等类型)
    一:新建springboot项目二:导包<dependencies><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</......
  • 【MybatisPlus】SpringBoot快速集成MybatisPlus
    目录一、引入依赖二、逆向生成工具类三、其他配置 一、引入依赖<!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-con......
  • Java开发学习(四十九)----MyBatisPlus更新语句之乐观锁
    1、概念在讲解乐观锁之前,我们还是先来分析下问题:业务并发现象带来的问题:秒杀假如有100个商品或者票在出售,为了能保证每个商品或者票只能被一个人购买,如何保证不会出......
  • MybatisPlus实现按年份动态操作表数据
    MybatisPlus实现按年份动态操作表数据 在mp的官方网站上最近的一次更新可以看到,其提供了动态表名插件:https://baomidou.com/pages/2a45ff/#dynamictablenameinnerinterce......