mybatis-plus简单使用

1.导包

<!-- mysql  驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.26</version>
</dependency>
<!--mybatisplus起步依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>

2.配置

# datasource
spring:
  datasource:
    url: jdbc:mysql://111.111.111.111:3306/mp?serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
mybatis-plus:
  global-config:
    db-config:
      # 表名前缀 实际表名就是前缀 + 类名
      table-prefix: tb_
      # id生成策略 数据库自增
      id-type: auto

启动类

@SpringBootApplication  //启动注解
@MapperScan("com.tang.mapper")
public class MybatisPlusSpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusSpringbootApplication.class, args);
    }
}

与表对应的类

  1. @Data
    @TableName("tb_user")//对应数据库中的哪个表
    public class User {

        @TableId(type = IdType.AUTO)    //数据库自增
        private Long id;

        @TableField("user_name")    //指定映射关系,名字相同或者 _ 换小驼峰 则会自动识别
        private String userName;

        private String password;
        private String name;
        private Integer age;
        private String email;

        @TableField(exist = false)      //忽略这个字段的查询和插入
        private String HaHa;
    }
 

分页查询:1.配置拦截器。2.创建page对象

@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
    mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    return mybatisPlusInterceptor;
}

 

分页查询

@Test
public void test05(){
    int page = 1;   //当前页数
    int size = 4;   //每页条数
    User user = new User();     //前台传过来的查询套件
    user.setUserName("zhangsan");
    QueryWrapper<User> queryWrapper =null;
    if(user!=null){
        //有条件再创建queryWrapper        这里相当于之前的动态sql
        queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(user.getUserName())){     //里面有值
            queryWrapper.eq("user_name",user.getUserName());
        }
        if(StringUtils.isNotBlank(user.getPassword())){     //里面有值
            queryWrapper.eq("password",user.getPassword());
        }
    }
    //分页查询
    Page<User> userPage = userMapper.selectPage(new Page<>(page, size), queryWrapper);

    List<User> records = userPage.getRecords();    //数据
    long total = userPage.getTotal();       //一共的条数
    long pages = userPage.getPages();       //一共的页数

    System.out.println(records);
    System.out.println(total);
    System.out.println(pages);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值