【MyBatis-Plus】MyBatis-Plus基本操作快速入门(二)

简介: 【MyBatis-Plus】MyBatis-Plus基本操作快速入门(二)

4.查询

4.1 Map条件

    @Test
    public void testMap(){
        Map map = new HashMap();
        map.put("cname","测试");
        map.put("password","123456");
        List list = customerMapper.selectByMap(map);
        list.forEach(System.out::println);
    }

4.2 Wrapper条件

4.2.1 wrapper介绍

image.png

Wrapper : 条件构造抽象类,最顶端父类

  • AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
  • QueryWrapper : Entity 对象封装操作类,不是用lambda语法

           UpdateWrapper : Update 条件封装,用于Entity对象更新操作

           AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column。

                LambdaQueryWrapper :看名称也能明白就是用于Lambda语法使用的查询Wrapper

                 LambdaUpdateWrapper : Lambda 更新封装Wrapper

  • 如果想进行复杂条件查询,那么需要使用条件构造器 Wapper,涉及到如下方法
方法名 描述
selectOne
selectCount
selectList
selectMaps
selectList
selectMaps
  • 拼凑条件相关关键字
查询方式 说明
setSqlSelect 设置 SELECT 查询字段
where WHERE 语句,拼接 + WHERE 条件
and AND 语句,拼接 + AND 字段=值
andNew AND 语句,拼接 + AND (字段=值)
or OR 语句,拼接 + OR 字段=值
orNew OR 语句,拼接 + OR (字段=值)
eq 等于=
allEq 基于 map 内容等于=
ne 不等于<>
gt 大于>
ge 大于等于>=
lt 小于<
le 小于等于<=
like 模糊查询 LIKE
notLike 模糊查询 NOT LIKE
in IN 查询
notIn NOT IN 查询
isNull NULL 值查询
isNotNull IS NOT NULL
groupBy 分组 GROUP BY
having HAVING 关键词
orderBy 排序 ORDER BY
orderAsc ASC 排序 ORDER BY
orderDesc DESC 排序 ORDER BY
exists EXISTS 条件语句
notExists NOT EXISTS 条件语句
between BETWEEN 条件语句
notBetween NOT BETWEEN 条件语句
addFilter 自由拼接 SQL
last 拼接在最后,例如:last(“LIMIT 1”)

4.2.2 条件查询

  • 基本多条件查询  
@Test
    public void testWrapper(){
        // 拼凑条件
        QueryWrapper<Customer> queryWrapper = new QueryWrapper();
        // 1)模糊查询
        queryWrapper.like("cname","测试");
        // 2)等值查询
        queryWrapper.eq("password","777");
        // 3)批量查询
        queryWrapper.in("cid",1,2,3,4);
        // 4) 范围
        queryWrapper.ge("money", 800);
        queryWrapper.le("money" , 1500);
        // 查询
        List<Customer> list = customerMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    }
  • 条件判断
  @Test
    public void findCondition2() {
        Customer customer = new Customer();
        customer.setPassword("777");
        customer.setCname("888");
        customer.setIdList(Arrays.asList(2,3,4));
        customer.setCid(3);
        //条件查询
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        // 1) 等值查询
        queryWrapper.eq( customer.getPassword()!=null ,"password", customer.getPassword());
        // 2) 模糊查询
        queryWrapper.like(customer.getCname() != null , "cname",customer.getCname());
        // 3) in语句
        queryWrapper.in(customer.getIdList() != null , "cid",customer.getIdList());
        // 4) 大于等于
        queryWrapper.ge(customer.getCid() != null , "cid" , customer.getCid());
        //查询
        List<Customer> list = customerMapper.selectList(queryWrapper);
        //list.forEach(customer-> System.out.println(customer));
        list.forEach(System.out::println);
    }

4.3.3 条件更新

  • 基本更新
@Test
    public void testWrapperUpdate(){
        //1 更新数据
        Customer customer = new Customer();
        customer.setVersion(1);
        //2 更新条件
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("cid", 1,2,3);
        //3 更新
        int update = customerMapper.update(customer, updateWrapper);
        System.out.println(update);
    }

4.3 分页

4.3.1 内置插件

主体插件: MybatisPlusInterceptor,该插件内部插件集:

  • 分页插件: PaginationInnerInterceptor
  • 多租户插件: TenantLineInnerInterceptor
  • 动态表名插件: DynamicTableNameInnerInterceptor
  • 乐观锁插件: OptimisticLockerInnerInterceptor
  • sql性能规范插件: IllegalSQLInnerInterceptor
  • 防止全表更新与删除插件: BlockAttackInnerInterceptor

4.3.2 配置类

image.png

package com.czxy.mp.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
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 {
    /**
     * 配置插件
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

4.3.3 分页

@Test
    public void testPage(){
        // 分页数据
        int pageNum = 1;
        int pageSize = 3;
        Page<Customer> page = new Page<>(pageNum , pageSize);
        page.setSearchCount(true);
        // 查询
        customerMapper.selectPage(page, null);
        // 分页数据
        System.err.println("当前页码:" + page.getCurrent());
        System.err.println("每页显示记录数:" + page.getSize());
        System.err.println("总页数:" + page.getPages());
        System.err.println("总记录数:" + page.getTotal());
        System.err.println("是否有下一页:" + page.hasNext());
        System.err.println("是否有上一页:" + page.hasPrevious());
        // 分页数据列表
        page.getRecords().forEach(System.err::println);
    }

5.常见注解

5.1 表名注解:@TableName

属性 描述
value 表名
keepGlobalPrefix 是否保持使用全局的 tablePrefix 的值(如果设置了全局 tablePrefix 且自行设置了 value 的值)

2.png

5.2 主键注解:@TableId

属性 描述
value 主键字段名
type 主键类型 IdType.ASSIGN_UUID ,分配UUID,MyBatisPlus维护String数据 IdType.ASSIGN_ID ,分配ID(默认使用雪花算法)MyBatisPlus维护Long数据 IdType.AUTO ,自动增长(数据库维护)
  • 测试表:User
CREATE TABLE tmp_user(
    uid VARCHAR(100),
    uname VARCHAR(50)
);
  • JavaBean
package com.czxy.mp.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    //@TableId(type = IdType.ASSIGN_UUID)   //随机一个字符串
    @TableId(type = IdType.ASSIGN_ID)     //随机一个数字(Long)
    private String uid;
    private String uname;
}

5.2 字段注解(非主键) : @TableField

属性 描述
value 数据库字段名
fill 字段自动填充策略 FieldFill.INSERT 插入时填充字段 FieldFill.UPDATE 更新时填充字段 FieldFill.INSERT_UPDATE 插入和更新时填充字段
exist 是否存储到数据库(是否是临时数据)

6.常见配置

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #输出日志
    map-underscore-to-camel-case: true  #驼峰命名
  global-config:
    db-config:
      id-type: auto  #全局配置,id自动增强
      table-prefix: tmp_ #表名前缀
  type-aliases-package: com.czxy.mp.domain #别名包扫描路径
  mapper-locations: classpath*:/mapper/**/*.xml #映射文件位置
  • 整合xml

image.png

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.czxy.mp.mapper.CustomerMapper">
    <select id="findAll" resultType="customer">
        select * from tmp_customer
    </select>
</mapper>
  • CustomerMapper对应的方法
package com.czxy.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.czxy.mp.domain.Customer;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface CustomerMapper extends BaseMapper<Customer> {
    public List<Customer> findAll();
}
相关文章
|
SQL 缓存 Java
Mybatis及MybatisPlus
MyBatis 是一款优秀的持久层框架,支持自定义 SQL、存储过程及高级映射。其系统架构通过 mybatis-config.xml 配置全局信息,结合 mapper.xml 映射 SQL 语句,构建 SqlSessionFactory 并创建 SqlSession 操作数据库。MyBatis 底层通过 Executor 执行器和 Mapped Statement 对象实现 SQL 的输入输出映射与执行。支持复杂结果集映射,
|
Java 数据库连接 mybatis
Springboot整合Mybatis,MybatisPlus源码分析,自动装配实现包扫描源码
该文档详细介绍了如何在Springboot Web项目中整合Mybatis,包括添加依赖、使用`@MapperScan`注解配置包扫描路径等步骤。若未使用`@MapperScan`,系统会自动扫描加了`@Mapper`注解的接口;若使用了`@MapperScan`,则按指定路径扫描。文档还深入分析了相关源码,解释了不同情况下的扫描逻辑与优先级,帮助理解Mybatis在Springboot项目中的自动配置机制。
1736 1
Springboot整合Mybatis,MybatisPlus源码分析,自动装配实现包扫描源码
|
Java 数据库连接 mybatis
成功解决: Invalid bound statement (not found) 在已经使用mybatis的项目里引入mybatis-plus,结果不能共存的解决
这篇文章讨论了在已使用MyBatis的项目中引入MyBatis-Plus后出现的"Invalid bound statement (not found)"错误,并提供了解决方法,主要是通过修改yml配置文件来解决MyBatis和MyBatis-Plus共存时的冲突问题。
成功解决: Invalid bound statement (not found) 在已经使用mybatis的项目里引入mybatis-plus,结果不能共存的解决
|
SQL Java 数据库连接
MyBatis-Plus快速入门:从安装到第一个Demo
本文将带你从零开始,快速入门 MyBatis-Plus。我们将首先介绍如何安装和配置 MyBatis-Plus,然后通过一个简单的示例演示如何使用它进行数据操作。无论你是 MyBatis 的新手还是希望提升开发效率的老手,本文都将为你提供清晰的指导和实用的技巧。
3630 0
MyBatis-Plus快速入门:从安装到第一个Demo
springboot整合mybatis-plus及mybatis-plus分页插件的使用
这篇文章介绍了如何在Spring Boot项目中整合MyBatis-Plus及其分页插件,包括依赖引入、配置文件编写、SQL表创建、Mapper层、Service层、Controller层的创建,以及分页插件的使用和数据展示HTML页面的编写。
springboot整合mybatis-plus及mybatis-plus分页插件的使用
|
SQL Java 数据库连接
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
idea中配置mybatis 映射文件模版及 mybatis plus 自定义sql
832 3
|
Java 数据库连接 Maven
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
文本,使用SpringBoot工程创建一个Mybatis-plus项目,Mybatis-plus在编写数据层接口,用extends BaseMapper<User>继承实体类
|
Java 数据库连接 API
后端开发之用Mybatis简化JDBC的开发快速入门2024及数据库连接池技术和lombok工具详解
后端开发之用Mybatis简化JDBC的开发快速入门2024及数据库连接池技术和lombok工具详解
443 3
|
Java 关系型数据库 MySQL
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
1376 0
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1888 1
Spring boot 使用mybatis generator 自动生成代码插件