葛雅隽 发表于 2025-6-2 00:31:50

Mybatis-Plus知识点详解

Mybatis-plus(简称MP),基于Mybatis的增强工具,保留了Mybatis的所有功能,同时增加了通用的CRUD,条件构造器,分页插件等等实用工具
特性


[*]即拿即用:通过通用Mapper和Service,无需编写XML既可以完成单表CURE操作
[*]Lambda支持:使用Lambda表达式构建查询条件,避免硬编码字段名,提升代码安全性
[*]更多的主键策略:支持多种主键生成方式,如雪花算法,自增等等
[*]分页插件:内置分页插件,支持多种数据库,简化分页查询操作
与Mybatis相比


[*]提供大量自动化功能,如通用的CRUD,条件构造器,分页支持极大减少操作代码,提高开发效率
[*]Mybatis需手动编写SQL,编写XML文件和映射接口DAO
快速入门

日志配置


[*]日志输出到标准输出流中
mybatis-plus:
# mapper配置文件
mapper-locations: classpath:mapper/*.xml
# resultType别名,没有这个配置resultType包名要写全,配置后只要写类名
type-aliases-package: com.mashang.springboot04.domain
//
configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl添加依赖与配置application.yml


[*]本人使用SpringBoot 2.7.18,JDK1.8:导入的依赖如下
      <dependency>
            <groupId>com.baomidou</groupId>
            mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.2</version>
      </dependency>

[*]application.yml如下:
# 也是springboot的配置文件,两个都可以用
server:
port: 8080
servlet:
    #配置根路径
    context-path: /
# 配置数据源
spring:
datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xiaomi_store?userSSL=false;serverTimezone=Asia/Shanghai
    username: root
    password: root
mybatis-plus:
# mapper配置文件
mapper-locations: classpath:mapper/*.xml
# resultType别名,没有这个配置resultType包名要写全,配置后只要写类名
type-aliases-package: com.mashang.springboot03.domain定义实体类与Mapper接口

实体类


[*]在实体类上使用Mybatis-plus的注解
[*]@TableName()→指定数据库查询的表,不添加默认将类名改为下划线型数据库名
[*]@TableId(name,type)→用于给主键标记,name为数据库对应名,用于指定自增算法

[*]雪花算法(Snowflake)是由Twitter开源的一种分布式ID生成算法.其核心思想是将64位的long型ID分为四个部分,分别为:符号位,时间戳,工作机器ID,序列号

@Data
@TableName("user")// 指定数据库表名
public class User {
    @TableId(type = IdType.AUTO)// 主键自增
    private Long id;
    private String name;
    private Integer age;
}Mapper接口


[*]Mapper接口需继承BaseMapper类,则此接口即可获得所有基本的CRUD方法
public interface UserMapper extends BaseMapper<User> {
    // 如果需要扩展自定义方法,也可以在此添加
}Service层与Service实现层

MP也提供了IService接口和ServiceImpl类方便在Service层使用封装好的CRUD方法
Service层


[*]extends(继承)IService接口
public interface UserService extends IService<User> {
    // 可以在此定义更多业务方法
}ServiceImpl层


[*]继承 ServiceImpl 和实现 IService 接口,可以直接调用封装好的 CRUD 方法
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 继承了 ServiceImpl 后,已拥有 BaseMapper 中所有的 CRUD 方法
}BaseMapper接口中常用的CRUD方法


[*]即Mapper层中的常见方法,已经集成好了,直接操作数据库的原子性方法
插入操作

// 插入一条记录
int insert(T entity);查询操作

// 根据 ID 查询T selectById(Serializable id);// 根据 entity 条件,查询一条记录T selectOne(@Param(Constants.WRAPPER) Wrapper queryWrapper);// 查询(根据ID 批量查询)List selectBatchIds(@Param(Constants.COLLECTION) Collection
页: [1]
查看完整版本: Mybatis-Plus知识点详解