MyBatisPlus 之三:BaseMapper 详解和 CRUD 案例详解

本文详细介绍了如何在MyBatisPlus中使用BaseMapper进行CRUD操作,包括配置SQL日志、基础增删改查API的使用,以及Wrapper的灵活条件查询、分页和主键管理。
摘要由CSDN通过智能技术生成

BaseMapper详解

1. SQL 日志开启

为了更好更快学习 MyBatisPlus ,需要配置 SQL 日志,这样方便我们能随时看到执行过程中使用的 SQL 语句,有助于理解执行原理及方便 SQL 错误调试

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

mybatis-plus.configuration.map-underscore-to-camel-case=false 

2. BaseMapper API

BaseMapper 是 MyBatis Plus 提供的一个通用接口,它定义了一套基础的 CRUD(Create, Read, Update, Delete)操作方法。通过继承 BaseMapper,开发者可以直接在自定义的 Mapper 接口中获得这些基本的数据操作功能,而无需手动编写 SQL 语句或 XML 映射文件。

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    int delete(@Param("ew") Wrapper<T> queryWrapper);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    int updateById(@Param("et") T entity);

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}

3 . 基本CRUD

1) 插入数据:
int insert(T entity);
/**
 * 1. 如果属性使用的是驼峰命名法时,生成SQL时,转为带下划线的列名。例如:bookName--book_name
 *   解决办法:
 *   a. 给属性添加注解 @TableField("bookName")
 *   b. 在配置文件中,关闭驼峰名和下划线的转换
 */
@Test
void save(){
    Book book = new Book();
    book.setPrice(34f);
    book.setAuthor("王超");
    book.setBookName("JSP开发技术");
    book.setPubDate(new Date());

    System.out.println(book);
    bookDao.insert(book);
    System.out.println(book);   //执行前 后 观察变化。主键
}

注意:

  1. 如果属性使用的是驼峰命名法时,生成SQL时,转为带下划线的列名。例如:bookName--book_name

    解决办法:

    a. 给属性添加注解 @TableField("bookName")

    b. 在配置文件中,关闭驼峰名和下划线的转换

    mybatis-plus.configuration.map-underscore-to-camel-case=false
  2. 如果指定了主键 @TableId 后,默认情况下(没有指定主键生成策略),主键会使用雪花算法生成应用于分布式系统的主键

    解决办法:

    a. 给主键指定生成策略 @TableId(value = "bookid",type = IdType.AUTO)

    b. IdType.AUTO : 主键生成有数据库端来完成,一般适用于数据库自动增长

type = IdType.INPUT :程序自己指定主键
type = IdType.ASSIGN_ID :由框架自动生成指定的主键,使用的是雪花算法
type = IdType.ASSIGN_UUID :有框架自动生成给定主键,使用算法 UUID 算法

除了AUTO 之外,都是程序指定的主键,又区分程序员自己指定还是框架自动生成。

2) 查询:
T selectById(Serializable id);

//根据指定的主键列表查询
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
//根据map中的key-value 作为条件等值条件查询
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
//根据构建的条件查询唯一一条记录对象
T selectOne(@Param("ew") Wrapper<T> queryWrapper);

//根据构建的条件 查询记录数
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
//根据构建的条件 查询多条记录
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);

如果直接使用 selectById() 查询,结果下面语句:

/**

 * 注意:给实体类中指定主键,否则出现下面 null=?
 * SELECT bookId,bookName,author,pubdate,price FROM book WHERE null=?
   */

查不出结果的原因:不知道哪一个列是主键。所以使用了 null = ? 作为条件了

解决办法:

给属性指定主键:@TableId

@TableField 可以设置忽略 exist=true

@Data
public class Book {
    @TableId
    private Integer bookId;
    @TableField("bookName")
    private String bookName;
    private Float price;
    @TableField("pubdate")
    private Date pubDate;
    private String author;
}
selectBatchIds() 用法:
//SELECT bookid,bookName,price,pubdate,author FROM book WHERE bookid IN ( ? , ? , ? , ? , ? )
List<Integer> ids = Arrays.asList(2,3,4,26,27);
bookDao.selectBatchIds(ids);
selectByMap() 用法:
//SELECT bookid,bookName,price,pubdate,author FROM book WHERE price = ? AND bookname = ?
Map<String,Object> cond = new HashMap<>();
cond.put("price",34f);
cond.put("bookname","Java开发技术");

bookDao.selectByMap(cond);
Wrapper 用法

下面方法用法:Wrapper 用法

//根据构建的条件 查询记录数
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
//根据构建的条件 查询多条记录
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

下面使用方式:

QueryWrapper 可以用于构建查询的列、条件、排序、分组等要素。

    void queryByWrapper(){
       QueryWrapper<Book> queryWrapper = new QueryWrapper<>();

       queryWrapper.select("bookname","price","author");     //指定要求查询的列
       queryWrapper.gt("price",20);                            // where price > 20
       queryWrapper.le("price",80);                            // and  price <= 80
       queryWrapper.eq("bookname","Java开发实战");             // and bookname= 'Java开发实战'
       queryWrapper.between("bookid",10,50);                // and bookid between 10,50 
       bookDao.selectList(queryWrapper);

//       bookDao.selectCount(null); //无条件查询,没有where
//        bookDao.selectCount(queryWrapper); //按条件查询
    }

queryWrapper 支持链式编程方式:

queryWrapper.select("bookname","price","author")
.gt("price",20)
.le("price",80)
.eq("bookname","Java开发实战")
.between("bookid",10,50);
bookDao.selectList(queryWrapper);
selectOne()

注意:返回值只能小于等于一条才可以,否则异常。

@Test
void queryOne(){
    QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("bookname", "Java实战开发1")
            .eq("author","周瑜");

    Book book = bookDao.selectOne(queryWrapper);
    System.out.println(book);
}
selectMaps()

返回结果为List ,元素为Map封装的记录对象。

@Test
void queryMap(){
    List<Map<String, Object>> maps = bookDao.selectMaps(null);
    maps.forEach(System.out::println);
}
or 和 orderby
/**
 * where author='周瑜' or author='诸葛亮'
 *
 * or 和 order by
 */
@Test
public void or(){
    QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("author","周瑜")
            .or()
            .eq("author","诸葛亮")
            .or()
            .gt("price",30f)
            .le("price",60f); // 默认为and 关系
    queryWrapper.orderByAsc("price").orderByDesc("bookid");

    bookDao.selectList(queryWrapper);
}
分页

分页需要考虑的要素:每页行数、总记录数、总页数、当前页号、当前页要显示记录

不同数据库分页 SQL 不同。

mysql : limit start, count;

sqlserver : top ---not in

oracle : rownum

MyBatisPlus 会根据 “方言” 配置,自动生成对应数据库的 SQL 语句去执行。

代码如下:

@Test
void page(){
    Page<Book> page = new Page<>();
    page.setSize(5);    //每页显示的记录数
    page.setCurrent(3); //设置当前页       // limit startindex ,countpage
    //(curPage-1)*size 

    Page<Book> page1 = bookDao.selectPage(page, null);
    //当前的要显示的记录
    List<Book> records = page1.getRecords();
    System.out.println(page1==page);
    records.forEach(System.out::println);
}

注意:直接运行后,发现并没有实现分页。

原因:没有安装分页插件。

解决办法:去官网,查看分页插件使用方法。复制代码到项目中即可

https://mp.baomidou.com/guide/page.html

//Spring boot方式
@Configuration
//@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    // 旧版
//    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //数据库方言
        return interceptor;
    }

}

2023最新版本的分页插件:

package com.wdzl.plus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 分页插件的配置
 */
@Configuration
public class MyBatisPlusConfig {

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

注意:

  1. 修改数据库方言(类型)

  2. 使用新版。注释掉旧版,不能同时使用。

  3. 类名和方法名可以自定义

另外:上面测试代码中

可以看到 page1==page 的输出结果为 true,说明两个是同一个对象。可以直接使用page 即可,简化后:

@Test
void page(){
    Page<Book> page = new Page<>();
    page.setSize(5);    //每页显示的记录数
    page.setCurrent(3); //设置当前页       // limit startindex ,countpage

    bookDao.selectPage(page, null);
    //当前的要显示的记录
    List<Book> records = page.getRecords();
    records.forEach(System.out::println);
}
3)修改
    //update book set price=99 where bookid=?
    int updateById(@Param("et") T entity);
    //update book set price=99 where bookname=? and price<?
    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
    @Test
    public void update(){
//        Book book = bookDao.selectById(27);
//        book.setPrice(88f);
//        bookDao.updateById(book); //按主键修改

        //下面是按条件修改
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("price",88);
        //注意 :book参数 ,是作为修改后的目标数据。把符合条件的所有记录都修改为book相同的值。

        Book book1 = new Book();
        book1.setPrice(100f);
        bookDao.update(book1,queryWrapper);
        //update 和 updateById() 在修改时,只修改属性不为null的列。
    }

注意:

  1. 单个对象修改,一般是先查询数据,再修改个别列。
  2. 对应null 的属性,不会被修改,不会执行SQL ,只会把有值的属性生成到SQL中。
4)删除
    //按主键删除 自注释
    int deleteById(Serializable id);
    //按map中的key-value 等值条件 删除
    int deleteByMap(@Param("cm") Map<String, Object> columnMap);
    // 根据构建条件删除
    int delete(@Param("ew") Wrapper<T> queryWrapper);
    // 根据集合中主键列表删除
    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
    @Test
    void delete(){
        Map<String,Object> map = new HashMap<>();
        map.put("price",44f);
        map.put("bookname","java开发");
//        bookDao.deleteByMap(map);

        //WHERE bookid IN ( ? , ? , ? , ? , ? , ? )
        List<Integer> ids = Arrays.asList(3,4,5,22,34,55);
//        bookDao.deleteBatchIds(ids);

        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt("price",30);
        bookDao.delete(queryWrapper);
   
  • 24
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Mybatis Plus是一个基于Mybatis的增强工具,可以在不改变Mybatis原有特性的基础上,提供更方便、更强大的功能,简化Mybatis的开发。 1. 常用功能 Mybatis Plus提供了很多实用的功能,包括: (1)CRUD操作:Mybatis Plus提供了通用的CRUD操作,无需编写Mapper.xml,只需要编写Mapper接口并继承BaseMapper即可。 (2)分页查询:Mybatis Plus提供了方便的分页查询功能,可以轻松实现分页查询。 (3)条件构造器:Mybatis Plus提供了条件构造器,可以使用Java代码构造查询条件,避免拼接SQL字符串。 (4)代码生成器:Mybatis Plus提供了代码生成器,可以根据数据库表自动生成实体类、Mapper接口、Mapper.xml等代码。 (5)性能分析插件:Mybatis Plus提供了性能分析插件,可以方便地分析SQL执行情况。 2. 使用方法 (1)依赖配置 在pom.xml中添加依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.1.2</version> </dependency> ``` (2)配置文件 在mybatis配置文件中添加Mybatis Plus的配置: ``` <configuration> <plugins> <!-- 分页插件 --> <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"/> </plugins> </configuration> ``` (3)使用方法 可以通过继承BaseMapper接口,使用Mybatis Plus提供的通用方法: ``` public interface UserMapper extends BaseMapper<User> { } ``` 也可以通过继承IService接口,使用Mybatis Plus提供的通用方法: ``` public interface UserService extends IService<User> { } ``` 3. 总结 Mybatis Plus简化了Mybatis的开发,提供了很多实用的功能,可以大大提高开发效率。建议在Mybatis开发中使用Mybatis Plus。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zp8126

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值