MybatisPlus详细讲解(适合新手和复习)

目录

一、什么是MybatisPlus

二、快速入门

2.1、添加依赖

2.2、配置连接数据库

2.3、编码

2.4、测试

三、配置日志

四、基本的CRUD操作

4.1、插入操作

4.2、更新操作

4.3、删除操作

五、自动填充

1.执行插入操作

2.执行修改操作

六、乐观锁和悲观锁

6.1、什么是乐观锁

6.2、什么是悲观锁

6.3、配置乐观锁

第一步:在数据库中user表添加一个version字段

第二步:在实力类中添加version并且在version字段上加@Version注解

第三步:编写mybatis-plus的配置类

4.测试

七、查询删除操作

7.1、查询操作

1.根据id查询用户

2.批量查询

3.条件查询

7.2、分页查询

7.3、删除操作

7.4、逻辑删除

1、在数据表中增加一个deleted字段

2、同步实体类,在实体类上加上@TableLogic 注解

3、配置application.yml文件

4、测试

5、对刚刚逻辑删除的id字段用户进行查询

八、执行SQL分析打印

8.1、添加组件依赖

8.2、修改pom依赖

8.3、spy.properties 配置

九、条件构造器

十、代码生成器

十一、在Mybatis-plus中是使用xml文件


一、什么是MybatisPlus

MybatisPlus可以节省大量时间,所有的CRUD代码都可以自动化完成。

MyBatis-Plus是一个MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生

特性:

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

继承 BaseMapper<I> 类,可以使我们的 Mapper 接口拥有这些通用的 CRUD 方法,Service也一样

  • 支持 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、快速入门

2.1、添加依赖

首先要创建一个springboot的工程这不需要多说了,还需要导入mysql的驱动依赖

以下为我初始化的时候选择的依赖

以下是mysql驱动和mybatis-plus的在springboot中的依赖

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

<!--mybatis-plus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

2.2、配置连接数据库

#mysql配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: wsndqd857857
    username: root
	#这里要更改数据库只需要更改voredb那个地方就可以了
    url: jdbc:mysql://localhost:3306/votedb?&useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

项目的文件夹如下:entity为实体类,mapper为操作数据库层

要进行mapper的扫描在启动类上加注解

@MapperScan("com.ltx.mybatis_plus.mapper")

这个地方一并的把数据库生成的文件也附上,创建数据库就自己点击创建吧这个地方就不给出代码咯~

create table user
(
    id          bigint auto_increment comment '主键'
        primary key,
    user_name   varchar(255)  null comment '用户名',
    password    varchar(255)  null comment '密码',
    phone       varchar(255)  null comment '手机',
    email       varchar(255)  null comment '邮箱',
    age         int           null comment '年龄',
    role        varchar(2)    null comment '角色',
    create_time datetime      null comment '创建时间',
    update_time datetime      null comment '修改时间',
    version     int default 1 null comment '乐观锁',
    deleted     int default 1 null comment '逻辑删除'
)
    charset = utf8mb3;

create table vote_theme
(
    id                bigint           not null comment '主题主键'
        primary key,
    theme_name        varchar(255)     null comment '主题名',
    theme_explain     text             null comment '相关说明',
    expectation_sum   bigint default 0 null comment '总期望值',
    expectation_times bigint default 0 null comment '期望人次',
    imgurl            varchar(2550)    null comment '主题图片',
    end_date          datetime         null,
    start_date        datetime         null,
    gmt_create        datetime         null comment '创建时间',
    gmt_modified      datetime         null comment '修改时间'
)
    charset = utf8mb3;

 数据生成的代码也写在下面了

INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1358687078200619010, 'wzp', '674f6e6d9b25a084110e992042ad0cdb', '17753657132', '1231@163.com', 22, 'a', '2022-11-22 20:53:35', '2023-11-22 20:53:35', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1358687341250588673, 'admin', '674f6e6d9b25a084110e992042ad0cdb', '17753657132', '124@163.com', 28, 'a', '2022-11-22 20:53:40', '2023-11-22 20:53:40', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1358687744079933441, 'wahahaa', '674f6e6d9b25a084110e992042ad0cdb', '18553777133', '123@126.com', 38, 'u', '2022-07-22 20:53:35', '2023-07-22 20:53:35', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1358693663190769666, 'hanjia', '674f6e6d9b25a084110e992042ad0cdb', '18577657134', '129@163.com', 18, 'u', '2022-05-22 20:53:35', '2023-05-22 20:53:35', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1362299967155175426, 'wanghia', '123', '123132', '2222', 18, 'u', '2022-02-22 20:53:35', '2023-02-22 20:53:35', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1362959351606640641, 'zhangsan', '674f6e6d9b25a084110e992042ad0cdb', '18453657775', '2222@qq.com', 40, 'a', '2022-08-22 20:53:35', '2023-08-22 20:53:35', 1, 0);
INSERT INTO votedb.user (id, user_name, password, phone, email, age, role, create_time, update_time, version, deleted) VALUES (1380808280388952066, '123123123', '674f6e6d9b25a084110e992042ad0cdb', '18553657776', '24423@qq.com', 18, 'u', '2022-01-22 20:53:35', '2023-01-22 20:53:35', 1, 0);

2.3、编码

编写实体类User.java(下面使用lombok的注解简化代码)

package com.ltx.mybatis_plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @author 罗添煦
 * @since 2023-11-22
 */
@AllArgsConstructor //有参构造
@NoArgsConstructor  //无参构造
@Data      //get、set方法和重新toString方法
@Accessors(chain = true)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    private String password;

    /**
     * 手机
     */
    private String phone;

    /**
     * 邮箱
     */
    private String email;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 角色
     */
    private String role;

}

编写mapper包下的UserMapper接口

package com.ltx.mybatis_plus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ltx.mybatis_plus.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

2.4、测试

在springboot的测试启动类中注入mapper接口,直接调用mybatis-plus帮我们封装好的crud接口就可以了

@SpringBootTest
class MybatisPlusApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> users = userMapper.selectList(null);
        System.out.println(users);     
    }

}

以下为输出

三、配置日志

如果你想要查看到具体的sql语句的话你可以使用yml配置开启日志

yml配置文件配置日志

#配置日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

四、基本的CRUD操作

首先我们需要了解的是在mybatis-plus中虽然不需要写xml配置的sql代码,但是还是需要知道是因为mp中帮我们已经封装好了一些需要的crud操作在上面也有提到,也就是如下图所示的,继承了BaseMapper接口,所以我们就可以看这个接口中到底给我们封装了那些curd操作。

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);   //插入操作

    int deleteById(Serializable id);  //指定id删除操作

    int deleteById(T entity);	

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

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

    int deleteBatchIds(@Param("coll") Collection<?> 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);

    default T selectOne(@Param("ew") Wrapper<T> queryWrapper) {
        List<T> ts = this.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(ts)) {
            if (ts.size() != 1) {
                throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records", new Object[0]);
            } else {
                return ts.get(0);
            }
        } else {
            return null;
        }
    }

    default boolean exists(Wrapper<T> queryWrapper) {
        Long count = this.selectCount(queryWrapper);
        return null != count && count > 0L;
    }

    Long 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);

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

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

我们可以看见这个接口中帮我们封装了基本上我们常用到的crud操作

4.1、插入操作

@Test
void contextLoads() {
    User user = new User();
    user.setAge(12);
    user.setEmail("1429189960@qq.com");
    user.setPassword("wsndqd857");
    user.setRole("学生");
    user.setPhone("18390205641");
    user.setUserName("罗添煦");
    userMapper.insert(user);
}

sql语句输出:

数据库插入结果

通过上面的数据库插入结果和sql语句的执行结果我们会发现我们在进行插入操作的时候,明明没有设置id的值呀,是怎么可以做到的有id的值而且还是刚刚好比最后一条数据的id大一的呢。

通过实体类我们可以发现一些端倪,在id字段上有@TableId(value = "id", type = IdType.AUTO),首先我们需要知道注解@TableId是用于标识实体类的属性与数据库表中主键字段的映射关系。

然后我们可以点入type查看有几种主键策略

1.AUTO(0):

  • 策略:自动增长。这意味着主键的值会自动递增,通常适用于整数型的主键。
  • 使用场景:当数据库中的主键设置为自增长时,可以使用此策略。

2.NONE(1):

  • 策略:没有主键。这表示实体类没有主键值,或者说不使用主键。
  • 使用场景:在某些情况下,可能不需要主键,或者在其他字段中定义复合主键时可以使用。

3.INPUT(2):

  • 策略:手动输入。这意味着在插入数据时需要手动指定主键的值。
  • 使用场景:适用于非自增、非UUID的主键类型,例如字符串或其他数据类型的主键。

4.ASSIGN_ID(3):

  • 策略:分配ID。这通常是由程序分配的一个长整型ID。
  • 使用场景:当需要使用程序中自定义的ID生成策略时,可以使用此选项。

5.ASSIGN_UUID(4):

  • 策略:分配UUID。这意味着主键的值将是一个生成的UUID。
  • 使用场景:当主键需要是UUID类型时,可以使用此策略。UUID可以确保全局唯一性,适用于分布式系统等场景。

4.2、更新操作

@Test
void contextLoads() {
    User user = new User();
    user.setId(1380808280388952067L);
    user.setUserName("罗添煦");
    userMapper.updateById(user);
}

会更加user中的id自动的去寻找修改的变量

4.3、删除操作

@Test
void contextLoads() {
    User user = new User();
    user.setId(1380808280388952067L);
    user.setUserName("罗添煦:更新版");
    userMapper.deleteById(user);
}

五、自动填充

我们现在设置user字段多添加两个字段一个是创建时间、一个是修改时间

对应在实体类User.java中也要加入字段

    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)   //使用的是插入策略
    private Date createTime;

    /**
     * 修改时间
     */
    @TableField(fill = FieldFill.UPDATE)
    private Date updateTime;

MetaObjectHandler我们需要自定义一个Handler实现此接口从而实现操作填充策略

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    //插入时候的策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime",new Date(),metaObject);
    }
    //修改时候的策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

更多内容可以去官网学习:

自动填充功能 | MyBatis-Plus

1.执行插入操作

继续调用我们上面使用的简单的插入操作的代码可以得到以下结果:

2.执行修改操作

调用修改方法会得到以下结果,执行了自动填充

六、乐观锁和悲观锁

6.1、什么是乐观锁

乐观锁的操作理念是“乐观”,它假设并发操作中数据冲突的可能性较小,因此在进行数据操作时不会直接锁定数据。只是在执行更新操作时,会判断在此期间是否有其他操作修改了数据。如果有其他操作修改了数据,那么乐观锁会放弃操作,否则执行操作。

6.2、什么是悲观锁

悲观锁的操作理念则相对“悲观”,它假设并发操作中数据冲突的可能性较大,因此在进行数据操作时会直接锁定数据,直到操作完成后才会释放锁。在锁定期间,其他操作不能修改数据,只能等待锁被释放。

6.3、配置乐观锁

本文主要讲解乐观锁机制

乐观锁实现方式:

  1. 取出记录时,获取当前version
  2. 更新时,带上这个version
  3. 执行更新时,set version = newVersion where version = oldVersion
  4. 如果version不对,就更新失败

第一步:在数据库中user表添加一个version字段

第二步:在实力类中添加version并且在version字段上加@Version注解

    @Version //乐观锁注解
    private int version;

第三步:编写mybatis-plus的配置类

package com.ltx.mybatis_plus.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.ltx.mybatis_plus.mapper")
public class MybatisPlusConfig {
    /**
     * 新版
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

4.测试

@Test
void contextLoads() {
    User user1 = userMapper.selectById(1380808280388952070L);
    user1.setUserName("罗添煦1");
    user1.setAge(19);

    User user2 = userMapper.selectById(1380808280388952070L);
    user2.setAge(20);
    user2.setUserName("罗添煦2");
    userMapper.updateById(user2);//当前插队操作会改变version的值本来version为1的,但是经过此次操作后version就会变成2

    userMapper.updateById(user1);//当前id中的version为2了,但是user1中保存的version还是1,所以这个地方就会操作失败
}

七、查询删除操作

7.1、查询操作

1.根据id查询用户

@Test
void contextLoads() {
    User user = userMapper.selectById(1380808280388952070L);
    System.out.println(user);
}

结果输出:

所以我们这个地方也可以有一个大胆的想法要是我们这个表里面的主键不是id那可不可以通过ById的方法查询到用户呢?

这个地方我们把id上的@TaableId注解移动到用户名头上我们看是不是也可以通过用户名来作为id查询到用户信息

@TableId(value = "user_name", type = IdType.NONE) //注意这个注解上的value要对应数据库中的字段名而不是采用小驼峰命名法
private String userName;
@Test
void contextLoads() {
    User user = userMapper.selectById("罗添煦2");
    System.out.println(user);
}

执行上面的代码得到结果和sql语句如下图所示:

但是最好是把这个注解写在主键上面。

2.批量查询

使用到的方法selectBatchIds()里面是传入的是一个集合。

@Test
void contextLoads() {
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1380808280388952070L,1380808280388952066L));
    System.out.println(users);
}

3.条件查询

map中的key作为对应数据库中的字段,value对应的是数据库中的值。

@Test
void contextLoads() {
    HashMap<String,Object> map = new HashMap<>();
    //自定义查询
    map.put("user_name","罗添煦2");
    map.put("age",20);
    List<User> users = userMapper.selectByMap(map);
    System.out.println(users);
}

结果如下:

7.2、分页查询

首先要使用分页查询就要先去配置分页查询的插件,所以我们需要在mybatisplus的配置类中先注册

/**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//如果配置多个插件,切记分页最后添加
        //interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); 如果有多数据源可以不配具体类型 否则都建议配上具体的DbType
        return interceptor;
    }
    <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);

首先我们需要从BaseMapper里面找到关于分页查询的方法,在此方法中我们看见了一个关于P继承了IPage的操作,我们需要查看这个IPage里面封装的是一些什么数据

当前页:+ page.getCurrent()
总页数:+ page.getPages()
记录数:+ page.getTotal()
是否有上一页: page.hasPrevious()
是否有下一页: page.hasNext()

对于第二个参数Wrapper<T> queryWrapper可以直接写null

@Test
void contextLoads() {
    // 两个参数:current的值默认是1,从1开始,不是0,指的是当前的页。size是每一页的条数。
    Page<User> page = new Page<>(2,3);
    Page<User> userPage = userMapper.selectPage(page, null);
    System.out.println(userPage.getRecords());
    System.out.println(userPage.getPages());
}

通过查看结果我们可以知道其实就是调用了一个分页查询,只是在内部封装帮你计算好是从那一个元素开始

//page的其他方法
System.out.println("当前页:" + page.getCurrent());
System.out.println("总页数:" + page.getPages());
System.out.println("记录数:" + page.getTotal());
System.out.println("是否有上一页:" + page.hasPrevious());
System.out.println("是否有下一页:" + page.hasNext());

结果为:

7.3、删除操作

跟查询操作相似,就不详细讲解

@Test
void contextLoads() {
    userMapper.deleteById(4L);
    //批量删除
    userMapper.deleteBatchIds(Arrays.asList(1L,2L));
    //通过map删除
    Map<String, Object> map = new HashMap<>();
    map.put("name","罗添煦");
    userMapper.deleteByMap(map);
}

7.4、逻辑删除

物理删除:从数据库中直接删除

逻辑删除:在数据库中没有被删除,而是通过一个变量来让它失效。 deleted=0 --->deleted=1

1、在数据表中增加一个deleted字段

2、同步实体类,在实体类上加上@TableLogic 注解

@TableLogic //逻辑删除
private Integer deleted;

3、配置application.yml文件

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

4、测试

在这里直接使用之前的delete测试

@Test
void contextLoads() {
    userMapper.deleteById(1380808280388952070L);
}

查看日志输出可以看到,delete的语句变成了update语句,实质上就是update(修改)语句,将deleted字段从0修改为1以yml的配置作为参照

5、对刚刚逻辑删除的id字段用户进行查询

//测试查询
@Test
public void testSelectById(){
    User user = userMapper.selectById(1380808280388952070L);
    System.out.println(user);
}

查看日志输出可以看到,seletc的语句以经发生了更改

增加了deleted的判断语句,判断deleted是否为0,为0则能搜索,1则不能。

八、执行SQL分析打印

p6spy 依赖引入

p6spy 组件的引入可以完美的输出打印 SQL 及执行时长用来解决新版的日志输出没有执行时间和完整的sql语句。

8.1、添加组件依赖

<dependency>
  <groupId>p6spy</groupId>
  <artifactId>p6spy</artifactId>
  <version>3.9.1</version>
</dependency>

8.2、修改pom依赖

#mysql配置
spring:
  datasource:
    password: wsndqd857857
    username: root
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:mysql:///votedb?userUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai

8.3、spy.properties 配置

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

执行刚刚的用id查找语句,完整代码如下:

九、条件构造器

完整的看官方文档: 条件构造器 | MyBatis-Plus

我们通过上面的简单的crud语句可以知道在mysql-plus中只可以进行一些最基础的操作需要进行复杂的操作还是得有其他的方法,这个地方的条件构造器就可以做到,下面就举一个复杂一点的查询的例子其他的语句操作可以看官网进行学习。

下面实现一个模糊查询的代码

@Test
void contextLoads() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();    //条件构造器
    wrapper.likeRight("user_name","罗");   //也就是 name  like '罗%'
    List<Object> users = userMapper.selectObjs(wrapper);
    System.out.println(users);
}

此代码执行的完整sql语句如下

如果有多条件也就只需给QueryWrapper构建多种条件即可。

十、代码生成器

此可以直接观看我的另一篇博客MyBatis-Plus代码生成器

十一、在Mybatis-plus中是使用xml文件

实际上在Mybatis-plus中使用xml文件也和在mybatis中使用xml文件一样的

首先我们需要创建mapper.xml文件与mapper文件进行绑定

<?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.ltx.mybatis_plus.mapper.UserMapper">  <!--不同的mapper文件需要改的地方就是这里-->


</mapper>

我们现在UserMapper中创建函数

@Mapper
public interface UserMapper extends BaseMapper<User> {
    String getUserName(Long id);
}

然后再xml中编写对应的映射

<select id="getUserName" parameterType="Long" resultType="String">
  select user_name from user where id = #{id}
</select>

如果在你的idea中下载了mybatis的插件你就可以看到有只红色的小鸟在边上也就是映射成功了

也就是这个插件

在测试类中测试编写的sql语句是否可用

@Test
void contextLoads() {
    System.out.println(userMapper.getUserName(1380808280388952070L));
}

测试输出完整代码如下:

SpringBootMybatisPlus的整合可以让我们更加方便地进行数据库操作,以下是详细的整合步骤: 1.在pom.xml文件中添加MybatisPlus和Clickhouse的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>ru.yandex.clickhouse</groupId> <artifactId>clickhouse-jdbc</artifactId> <version>0.3.1</version> </dependency> ``` 2.在application.properties文件中添加Clickhouse的配置: ```properties spring.datasource.driver-class-name=ru.yandex.clickhouse.ClickHouseDriver spring.datasource.url=jdbc:clickhouse://localhost:8123/default spring.datasource.username=default spring.datasource.password= ``` 3.创建实体类和Mapper接口,使用MybatisPlus的注解来简化代码: ```java @Data public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; } @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 4.在Service中注入Mapper,并使用MybatisPlus提供的方法进行数据库操作: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> listUsers() { return userMapper.selectList(null); } @Override public User getUserById(Long id) { return userMapper.selectById(id); } @Override public void saveUser(User user) { userMapper.insert(user); } @Override public void updateUser(User user) { userMapper.updateById(user); } @Override public void deleteUser(Long id) { userMapper.deleteById(id); } } ``` 5.在Controller中注入Service,并编写接口方法: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("") public List<User> listUsers() { return userService.listUsers(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("") public void saveUser(@RequestBody User user) { userService.saveUser(user); } @PutMapping("") public void updateUser(@RequestBody User user) { userService.updateUser(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

用草书谱写兰亭序

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

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

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

打赏作者

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

抵扣说明:

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

余额充值