MyBatis-Plus快速入门篇

news2024/10/2 16:24:30

入门篇

  • 1.快速入门
    • 1.1数据库准备
    • 1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程
    • 1.3编写DataSource相关配置(配置MySQL数据库连接)
    • 1.4编码
    • 1.5测试
  • 2.使用MybatisPlus完成增删改
    • 2.1Mapper添加
    • 2.2Mapper删除
    • 2.3Mapper修改
  • 3.使用MybatisPlus完成查询
  • 4.Service封装
  • 5.逆向工程-代码生成器

1.快速入门

1.1数据库准备

现有一张tb_user表,其表结构如下:
在这里插入图片描述
对应的数据库脚本如下:

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

1.2创建SpringBoot工程,引入MyBatis-Plus和MySQL依赖,可以使用 Spring Initializer快速初始化一个 Spring Boot 工程

<?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>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mybatisplus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisplus</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

1.3编写DataSource相关配置(配置MySQL数据库连接)

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8

1.4编码

实体类

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@TableName("tb_user")
@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

其中@TableName是MybatisPlus注解,内容对应MySQL表名称,@Data是Lombok的注解,该注解的主要功能是省去了getter/setter方法。

编写mapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.domain.User;

public interface UserMapper extends BaseMapper<User> {
}

启动类增加@MapperScan注解

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mybatisplus")
public class MybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }

}

1.5测试

import com.example.mybatisplus.domain.User;
import com.example.mybatisplus.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = MybatisplusApplication.class)
@RunWith(SpringRunner.class)
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test01(){
        User user = userMapper.selectById(1);
        System.out.println(user);
    }
}

在这里插入图片描述

@Test需引入Junit依赖包,可以从https://mvnrepository.com/下载

2.使用MybatisPlus完成增删改

2.1Mapper添加

方法:

    //添加一条记录 参数:T 实体对象
    int insert(T entity);

测试:

    @Test
    public void testInsert(){
        User user=new User();
        user.setUsername("xy");
        user.setPassword("123456");
        user.setName("专精装项羽");
        user.setAge(180);
        int count = userMapper.insert(user);
        System.out.println(count);
    }

2.2Mapper删除

方法:

    //根据ID删除
    int deleteById(Serializable id);
    //根据实体类删除
    int deleteById(T entity);
    //根据columnMap条件删除
    int deleteByMap(@Param("cm") Map<String, Object> columnMap);
    //根据entiy条件,删除记录
    int delete(@Param("ew") Wrapper<T> queryWrapper);
    //根据ID批量删除
    int deleteBatchIds(@Param("coll") Collection<?> idList);

测试:

根据id删除

    @Test
    public void testDelete01(){
        int count=userMapper.deleteById(1883332609);
    }

根据id批量删除

    @Test
    public void testDelete02(){
        List list=new ArrayList();
        list.add(3);
        list.add(4);
        int count = userMapper.deleteBatchIds(list);
    }

根据map构造条件,删除

    @Test
    public void testDelete03(){
        Map<String,Object> map=new HashMap<>();
        map.put("username","dg");
        map.put("name","呆瓜");
        int count = userMapper.deleteByMap(map);
    }

2.3Mapper修改

方法:

    //根据ID修改
    int updateById(@Param("et") T entity);
    //根据whereEntiy条件修改
    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

测试:

    @Test
    public void testUpdate01(){
        User user=new User();
        user.setId(3);
        user.setName("杨杨杨");
        int count = userMapper.updateById(user);
    }

    @Test
    public void testUpdate02(){
        User user=new User();
        user.setName("旺旺旺");
        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.eq("id",1);
        int count = userMapper.update(user,qw);
    }

3.使用MybatisPlus完成查询

查询的方法比较多,所以单独总结一起

    //根据ID查询,查询出一条记录
    T selectById(Serializable id);
    //根据ID批量查询,查询出多条记录
    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
    //根据entity条件,查询出多条记录
    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
    //根据columnMap条件,查询出多条记录
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
    //根据queryWrapper条件,查询出多条记录
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
    //根据queryWrapper条件,查询出多条记录(注意:只返回第一个字段的值)
    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
     //根据entiy条件,查询出多条记录并分页
    <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);
    //根据Wrapper条件,查询出多条记录并分页
    <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);

分页查询
配置拦截器

@Configuration
public class PageConfig {

    /**
     * 3.4.0之前的版本用这个
     * @return
     */
   /* @Bean
    public PaginationInterceptor paginationInterceptor(){
        return  new PaginationInterceptor();
    }*/

    /**
     * 3.4.0之后提供的拦截器的配置方式
     * @return
     */
   @Bean
   public MybatisPlusInterceptor mybatisPlusInterceptor(){
       MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
       mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
       return mybatisPlusInterceptor;
   }
}

查询

    @Test
    public void testSelectPage(){
        int current=1;//当前页码
        int size=5;//每页显示条数
        IPage<User> page=new Page(current,size);
        userMapper.selectPage(page,null);
        List<User> records = page.getRecords();//当前页的数据
        long pages = page.getPages();//总页数
        long total = page.getTotal();//总记录数
        System.out.println(records);
        System.out.println(pages);
        System.out.println(total);
    }

条件构造器查询

Wrapper:
    1.QueryWrapper 查询
        LambdaQueryWrapper (支持Lambda表达式)
    2.UpdateWrapper 更新
        LamdbaUpdateWrapper(支持Lamdba表达式)    

基础查询
通过QueryWrapper指定查询条件

sql:select * from tb_user where password='123456' and age>18
eq():等于=
ne():不等于=
gt():大于>
ge():大于等于>=
lt():小于<
le():小于等于<=
between(): BETWEEN1 AND2
in():in
notIn():not in
    @Test
    public void testWrapper1(){
        //创建查询条件构造器
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        //设置条件
        wrapper.eq("username","bq")
                .lt("age",23)
                .in("name","白起","旺旺旺");
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);
     }

以上sql等同于 select * from tb_user where username=“bq” and age<23 and name in(“白起”,“旺旺旺”)

逻辑查询or
or():让紧接着下一个方法用or连接

    @Test
    public void testWrapper2(){
        //创建查询条件构造器
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        //设置条件
        wrapper.eq("username","bq")
                .or()
                .lt("age",23)
                .in("name","王昭君","旺旺旺");
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);
    }

模糊查询like

like      //模糊查询匹配值‘%值%’
notLike   //模糊查询不匹配值‘%值%’
likeLeft  //模糊查询匹配最后一位值‘%值’
likeRight  //模糊查询匹配第一位值‘值%’
    @Test
    public void testWrapper3(){
        //创建查询条件构造器
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        //设置条件
        wrapper.likeLeft("name","君");
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);
    }


排序查询

orderBy
orderByAsc
orderByDESC

select:指定需要查询的字段

    @Test
    public void testWrapper4(){
        //创建查询条件构造器
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        //设置条件
        wrapper.lt("age",22).select("age");
        List<User> users = userMapper.selectList(wrapper);
        System.out.println(users);
    }

4.Service封装

MVC架构
controller---->service(impl)------->dao(mapper)

Mybatis-Plus 为了开发更加快捷,对业务层也进行了封装,直接提供了相关的接口和实现类。我们在进行业务层开发时,可以继承它提供的接口和实现类,使得编码更加高效

    1. 定义接口继承IService
    1. 定义实现类继承ServiceImpl<Mapper,Entity> 实现定义的接口

接口

public interface _UserService extends IService<User> {
}

实现类实现接口

@Service
public class _UserServiceImpl extends ServiceImpl<UserMapper, User> implements _UserService {}

测试

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mybatisplustest.MybatisPlusTestApplication;
import com.example.mybatisplustest.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = MybatisPlusTestApplication.class)
@RunWith(SpringRunner.class)
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testFind(){
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",1);
        User one = userService.getOne(wrapper);
        System.out.println(one);
    }
}

5.逆向工程-代码生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
安装
引入坐标依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>
package com.example.mybatisplus;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Collections;

public class Generator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "123456")
                .globalConfig(builder -> {
                    builder.author("test") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("D://"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
                            .moduleName("system") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("tb_user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

生成结果
在这里插入图片描述
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/352497.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【论文阅读】Frustratingly Simple Few-Shot Object Detection

从几个例子中检测稀有物体是一个新出现的问题。 先前的工作表明Meta-Learning是一种有希望的方法。 但是&#xff0c;微调技术很少引起注意。 我们发现&#xff0c;在稀有类上只对现有探测器的最后一层进行微调对于 Few-Shot Object Detection至关重要。 这样一种简单的方法在当…

Yaklang XSS 检测启发式算法(被动扫描插件)

背景 上一篇介绍了XSS 启发式检测基础设施&#xff0c;本篇通过yak提供的基础设施编写一个xss检测插件。 本次xss靶场使用pentesterlab的xss靶场。 环境部署 git clone https://github.com/yaklang/vulinone cd php-web-for-pentester docker-compose up -d编写思路 参考上…

matlab-汽车四分之一半主动悬架模糊控制

1、内容简介汽车四分之一半主动悬架模糊控制651-可以交流、咨询、答疑2、内容说明半主动悬架汽车 1/4 动力学模型建立 本章主要对悬架类型进行简要介绍&#xff0c;并对其进行对比分析&#xff0c;提出半主动悬架的优越性&#xff0c;论述半主动悬架的工作原理&#xff0c;并对…

语音播报警示器技术要求

功能概述&#xff1a; 本系统采用30W太阳能板给12AH铅酸胶体电池充电&#xff1b;通过人体红外探测传感器&#xff0c;能感应到12米范围内有人有车经过&#xff0c;就触发播报防火宣传的语音&#xff0c;并且大红闪灯同步闪烁警示&#xff1b;高清双侧宣传牌&#xff0c;宣传内…

XSS注入基础入门篇

XSS注入基础入门篇1.XSS基础概念2. XSS的分类以及示例2.1 反射型XSS2.1.1 示例1&#xff1a;dvwa low 级别的反射型XSS2.1.2 攻击流程2.2 DOM型XSS2.2.1 示例2&#xff1a;DOM型XSS注入1.环境部署2.基础版本3.进阶绕过2.3 存储型XSS2.3.1 示例1&#xff1a;dvwa low示例2.3.2 攻…

WebADI - 参数的使用

* 本文仅供交流分享&#xff0c;不作为专业指导 最近研究了一下WEBADI文档下载的参数&#xff0c;由于网上这块资料较少&#xff0c;所以专意分享下我的笔记。 准备 集成器&#xff1a;BHSC_EMP_ADI 表值集&#xff1a;BHSC_DEPT_LOV&#xff08;值&#xff1a;dname&#x…

c++学习笔记-提高编程-模板(哔站-黑马程序员c++教学视频)

目录 1、模板概念 2、模板特点 3、模板语法 3.1编程思想&#xff1a;泛型编程 3.2两种模板方法&#xff1a; 3.2.1 函数模板 3.2.2 类模板 1、模板概念 通用的模具&#xff0c;提高代码复用性 2、模板特点 不可以直接使用&#xff0c;只是一个框架&#xff1b;模板的…

JMeter 做接口性能测试,YYDS

简介 本文由xmeter君写给想了解性能测试和JMeter的小白&#xff0c;适合对这两者了解很少的同学们&#xff0c;如果已经有使用经验的请绕道&#xff0c;别浪费时间:-) 我们将介绍JMeter的使用场景&#xff0c;如何安装、运行JMeter&#xff0c;以及开始一个最最简单的测试。 …

房产|1月全国70城房价出炉!疫情放开后你关心的城市房价有何变化

2023年1月份&#xff0c;70个大中城市中新房销售价格环比上涨城市个数增加&#xff1b;一线城市新房销售价格环比同比转涨、二三线城市环比降势趋缓&#xff0c;二三线城市同比下降。 | 新房/二手房12月-1月环比上涨城市数量变化 70个大中城市中&#xff0c;新房环比上涨城市…

RBAC(Role-Based Access Control:基于角色的访问控制)

RBAC是什么 1、RBAC模型概述 RBAC模型&#xff08;Role-Based Access Control&#xff1a;基于角色的访问控制&#xff09;模型是20世纪90年代研究出来的一种新模型&#xff0c;但其实在20世纪70年代的多用户计算时期&#xff0c;这种思想就已经被提出来&#xff0c;直到20世…

控制层类上的注解、业务层的注入、URL映射、参数接收、返回数据及网页模板、RESTful

控制类的作用&#xff1a; 处理http的请求&#xff0c;从HTTP请求中获得信息&#xff0c;提取参数&#xff0c;并分发给不同的处理服务&#xff0c;处理之后封装成一个Model &#xff0c;然后再把该Model返回给对应的View进行展示。 控制层类上的注解 Controller&#xff1a;…

科技爱好者周刊之爱好者记录

前言 平时浏览的内容杂七杂八&#xff0c;说好听一些叫做“内容丰富&#xff0c;涉猎甚广”&#xff0c;实际一些则是受到主流大环境的冲击加之自身的控制力尚且不足。 有过类似经历的人大多知道&#xff0c;碎片化的信息除了填充大脑的冗余空间&#xff0c;在短期时间内就会被…

AMBA低功耗接口规范(Low Power Interface Spec)

1.简介 AMBA提供的低功耗接口&#xff0c;用于实现power控制功能。目前AMBA里面包含2种低功耗接口&#xff1a; Q-Channel&#xff1a;实现简单的power控制&#xff0c;如上电&#xff0c;下电。 P-Channel&#xff1a;实现复杂的power控制&#xff0c;如全上电&#xff0c;半上…

今天面了个腾讯拿28K出来的,让我见识到了测试基础的天花板...

公司前段缺人&#xff0c;也面了不少测试&#xff0c;结果竟然没有一个合适的。 一开始瞄准的就是中级的水准&#xff0c;也没指望来大牛&#xff0c;提供的薪资在10-20k&#xff0c;面试的人很多&#xff0c;但平均水平很让人失望。 看简历很多都是3年工作经验&#xff0c;但…

每天10个前端小知识 【Day 17】

前端面试基础知识题 1.使用原生js实现以下效果&#xff1a;点击容器内的图标&#xff0c;图标边框变成border:1px solid red&#xff0c;点击空白处重置 const box document.getElementById(box); function isIcon(target) { return target.className.includes(icon); } b…

【Unity VR开发】结合VRTK4.0:设置抓取时可交互对象的方向

语录&#xff1a; 取酒酿晚风&#xff0c;赠我一场空。 前言&#xff1a; 获取可交互对象的默认方法是将可交互对象的原点与交互器的原点对齐。此机制适用于基本抓取&#xff0c;但有时当您想要抓取某个对象时&#xff0c;您可能希望将可交互对象定向到特定位置并旋转到交互器…

【免费教程】SWAT模型及在面源污染中的应用与案例分析

SWATSWAT&#xff08;Soil and Water Assessment Tool&#xff09;是由美国农业部&#xff08;USDA&#xff09;的农业研究中心Jeff Arnold博士1994年开发的。模型开发的最初目的是为了预测在大流域复杂多变的土壤类型、土地利用方式和管理措施条件下&#xff0c;土地管理对水分…

mysql 按时间倒排序深翻页思考

背景深翻页&#xff0c;可以用id做为偏移量&#xff0c;但如果是uuid时&#xff0c;或需求是要按时间排序时&#xff0c;深翻页就是一个问题了。如果要按最后修改时间倒排序&#xff0c;把时间做索引是可以&#xff0c;但有可能时间是有重的&#xff0c;这样结果就可能不准确这…

【Deformable Convolution】可变形卷积记录

every blog every motto: You can do more than you think. https://blog.csdn.net/weixin_39190382?typeblog 0. 前言 可变形卷积记录 1. 正文 预印版&#xff1a; Deformable Convolutional Networks v1 Deformable ConvNets v2: More Deformable, Better Results 发表版…

【郭东白架构课 模块一:生存法则】05|法则二:研发人员的人性需求是如何影响架构活动成败的?

你好&#xff0c;我是郭东白。上节课我们学习了马斯洛关于人性的理论&#xff0c;那么这节课我们就利用这个理论来看看我们在架构活动中应该注意些什么。 架构设计必须符合人性&#xff0c;而在架构活动中&#xff0c;与“人”相关的主要就是研发人员和目标用户。那么今天这节…