mybatis-plus入门(springboot版)

一、简介

​ 官方文档:MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

​ 总结:使用mybatis-plus并不影响mybatis的使用。

特性(官方文档):

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、配置

1、Maven依赖

​ 其中mybatis-plus的必要依赖是mybatis-plus依赖:mybatis-plus-boot-starter 和mysq依赖:mysql-connector-j ,其中jdbc依赖已经在mybatis-plus依赖中集成了不需要导入。

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!-- Generated by https://start.springboot.io -->
    <!-- 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn -->
    <groupId>com.zhangxin</groupId>
    <artifactId>First</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>First</name>
    <description>First</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
<!--        thymeleaf引擎模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--       lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<!--        hutool工具库-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.25</version>
        </dependency>
<!-- mybatis plus -->
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>
<!--      mysql依赖-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <image>
                        <builder>paketobuildpacks/builder-jammy-base:latest</builder>
                    </image>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、application.yml

​ springboot核心配置文件,可以使用连接池这里就是原生的jdbc连接。

server:
  port: 8080

spring:
  datasource:
    username: root
    password: 1234567
    url: jdbc:mysql://@localhost:3306/mybatisplus?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  #扫描所有的mapper.xml,使其生效
  mapper-locations: classpath:/mapper/**/*.xml
  #扫描实体类所在的包,使其产生别名,在mapper.xml中就没必要使用全类名指定返回或参数类型,直接填类名即可
  type-aliases-package: com.zhangxin.first.pojo
  configuration:
    #开启数据库的下划线命名转驼峰命名,(默认也是开启)
    map-underscore-to-camel-case: true
    #关闭二级缓存(默认也是关闭)
    cache-enabled: false
#    开启日志,使执行的说起来语句显示到控制台
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#    mybatis-plus全局配置,如果有代码内部注释也配置了,注释的配置优先级更高
  global-config:
    db-config:
#     主键添加方式这里是使用主键自动增长,默认是雪花算法生成主键
      id-type: auto

3、数据库表

三、使用

1、实体类

​ 实体类对应的是数据库中的表,mybatis-plus会将实体类的类名和数据库中的表进行匹配,进而可以通过实体类对表进行一些配置。

  • @TableName(“”),一般情况下实体类名和表名一致这样mybatis-plus会自动识别,但是在名字不同的情况下就需要我们主动标记其中@TableName中的value就是我们需要对应表名。

  • @TableId(“”) 当主键名称为id时mybatis-plus会自动将其作为主键,其中的value是对应表中主键的字段名,type可以规定主键的生成策略。

    type的值描述
    IdType.AUTO主键自增
    IdType.NONE不使用主键生成策略
    IdType.INPUT用户手动输入
    IdType.ASSIGN_ID雪花算法生成id,适用于( Long、Integer、String)
  • @TableField 默认情况下开启了下划线转驼峰命名,所以属性名和字段名会自动匹配,当即使转换后名字也不同时就需要手动给属性对应其表中的字段了,value表示数据库字段名,exit表示是否存在于表中。

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
//    自增长
    @TableId(value = "u_id",type = IdType.AUTO)
    private Integer uId;
    @TableField("u_name")
    private String uName;
    private String uPassword;
    private Integer age;
    private String sex;
    private String email;
}

2、mapper接口

(1)介绍

​ 需要继承 BaseMapper<>,它已经实现了大量的方法执行sql语句,只需要规定泛型是对应表的实体类即可。

​ 使用**@mapper注解或者@mapperScan(“”)**注解将mapper注入到spring容器中,其中@mapper注解是对于一个实体类,@mapperScan(“”)是扫描包。

​ mapper接口中可以自定义方法并写到mapper.xml中,但是那只是对于复杂的sql,大部分语句 BaseMapper<>已经实现了

@Mapper
public interface UserMapper extends BaseMapper<User> {
    List<User> getAllUserList();
}

(2)Test

使用mybatis-plus自带的方法:

@Resource
UserMapper userMapper; 
@Test
void contextLoads() {
  userMapper.selectList(null).forEach(user -> {
    System.out.println(user);
  });

}

使用自定义mapper.xml的方法

userMapper.xml

<?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">
<!--namespace要和一个接口的全类名一致-->
<!--<mapper namespace="com.zhangxin.myBatis.mapper.ParameterMapper">-->
<mapper namespace="com.zhangxin.first.mapper.UserMapper">
    <select id="getAllUserList" resultType="user">
        select * from user;
    </select>
</mapper>

test:

@Resource
UserMapper userMapper; 
@Test
void test1(){
  userMapper.getAllUserList().forEach(user -> {
    System.out.println(user);
  });
}

3、service层

(1)介绍

​ IService 接口是mybatis-plus的service的通用接口,ServiceImpl是 IService 默认实现类,ServiceImpl 是针对业务逻辑层的实现,并调用 BaseMapper 来操作数据库,对于自定义的方法也可以使用BaseMapper来使用。

userService:

public interface UserService  extends IService<User> {
    List<User> getAllUserList();
}

userServiceImp

​ 其中的this.baseMapper相当于泛型参数里的UserMapper。

//泛型中传入对应的Mapper,ServiceImpl可以自动调用mapper实现的方法,相当于自动帮你注入mapper了
@Service
public class UserServiceImp extends ServiceImpl<UserMapper,User> implements UserService {
    @Override
    public List<User> getAllUserList() {
        return this.baseMapper.getAllUserList();
    }
}

(2)Test

@Resource
UserService userService; 
@Test
void testService(){
  userService.list().forEach(user -> {
    System.out.println(user);
  });
}

4、controller层

直接调用service层即可

四、条件构造器(Wapper)

1、简介

​ Wrapper是MyBatis-Plus中的一个通用抽象接口,用于封装查询或更新的条件。它提供了一系列用于构建条件的方法,可以链式调用,方便进行多条件组合。QueryWrapper和UpdateWrapper是最常用的Wapper实现类。

2、QueryWrapper

​ 用于构建查询条件

@Test
void testWrapper1(){
  //构建查询条件
  QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>()
    .select("u_name","sex","email")//查询的字段
    .like("u_name","m")//模糊匹配u_name中有字母m的
    .ge("age",15);//age大于等于15的
  //      查询
  userMapper.selectList(userQueryWrapper).forEach(user -> {
    System.out.println(user);
  });
}

相当于sql:

select u_name,sex,email 
from 表名 
where age>=15 and u_name like '%m%';

3、UpdateWrapper

​ 用于构建更新条件

 @Test
    void testWrapper2(){
       // 更新,名为张三的人更新
        User user=new User(10,"张三","123",45,"男","123@qq.com");
        QueryWrapper<User> uId = new QueryWrapper<User>().eq("u_name", "张三");
        userMapper.update(user,uId);
    }

相当于sql:

update 表名 
set u_id=10,u_name='张三',u_password='123',age=45,sex='男',emile='123@qq.com'
where u_name='张三';

4、函数

​ 引用博客:https://blog.csdn.net/qq_39715000/article/details/120090033

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值