Springboot接入MyBatisPlus

1、什么是MyBatisPlus?

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

通过封装一些基础通用的curd方法,我们不用再在xml文件中编写sql语句,就可以直接调用api进行对数据库的操作。

2、MyBatisPlus环境准备

   2.1 创建一个springboot项目,在pom文件下添加如下依赖:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>
    2.2 创建一个包用来存放 mapper 文件

    2.3 在 Spring Boot 主类上面使用 @MapperScan 注解扫描我们自定义的 mapper

    2.4 自定义自己的 mapper,该 mapper 将继承 com.baomidou.mybatisplus.core.mapper.BaseMapper

    2.5 在我们的服务中使用 @Autowired 注解自动注入自定义的 mapper

3、具体使用

    3.1 基础使用
@Mapper
public interface OnlinePriceMapper extends BaseMapper<OnlinePrice> {

}

mapper中没有定义任何方法

package com.online.analyze.service.impl;

import com.online.analyze.mapper.OnlinePriceMapper;
import com.online.analyze.model.OnlinePrice;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author lijianxi
 * @date 2022年03月18日 11:13 上午
 */
@SpringBootTest
public class MapperTest {
    @Autowired
    OnlinePriceMapper onlinePriceMapper;

    @Test
    public void testMapper() {
        OnlinePrice onlinePrice = new OnlinePrice();
        onlinePrice.setId(3999222L);
        onlinePrice.setAddDate(new Date());
        onlinePrice.setDescription("test");
        onlinePrice.setSummary("test");
        onlinePrice.setProcessMethod("修改数据");
        //新增
        int result = onlinePriceMapper.insert(onlinePrice);
        if (result > 0) {
            System.out.println("插入成功");
        }
        //查询
        OnlinePrice price = onlinePriceMapper.selectById(3999222L);
        System.out.println(price.getDescription() + "查询成功");
        //更新
        onlinePrice.setDescription("修改后");
        onlinePriceMapper.updateById(onlinePrice);
        System.out.println(onlinePriceMapper.selectById(3999222L).getDescription() + "修改成功");
        //删除
        if (onlinePriceMapper.deleteById(3999222L) > 0) {
            System.out.println("删除成功");
        }


    }
}

通过注入mapper,就可以使用 mapper 的 insert(插入)、selectById(根据ID查找)、updateById(根据ID更新)和 deleteById(根据ID删除)等简单的 CRUD 操作

常用的增删改查方法可以查看BaseMapper接口

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

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

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

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

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

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

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

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
3.2 wapper构建

除了通过已定义的方法来查询还可以通过 Wrapper 构建查询条件

@Test
    public void testMapper(){
        //查询id为3999222数据信息
        QueryWrapper<OnlinePrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", 3999222L);
        OnlinePrice onlinePrice = onlinePriceMapper.selectOne(queryWrapper);
        System.out.println(onlinePrice.getId());
        //查询添加日期在区间内并且user_city不为null的数据
        QueryWrapper<OnlinePrice> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.between("add_date","2022-02-02","2022-02-10");
        queryWrapper1.isNotNull("user_city");
        String summary ="test";
        // 第一个参数为是否执行条件,为true则执行该条件
        queryWrapper1.eq(StringUtils.isNotBlank(summary),"summary",summary);
        List<OnlinePrice> onlinePrices = onlinePriceMapper.selectList(queryWrapper1);
        for (OnlinePrice price : onlinePrices) {
            System.out.println(price);
        }
    }
3.3分页功能
@Test
    public void testPage() {
        QueryWrapper<OnlinePrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("description");
        //每页四个
        Page<OnlinePrice> page = new Page<>(1, 4);
        Page<OnlinePrice> onlinePricePage = onlinePriceMapper.selectPage(page, queryWrapper);
        for (OnlinePrice record : page.getRecords()) {
            System.out.println(record);
        }
    }
3.4 service层接口

除了 BaseMapper 接口,MyBatis Plus 还提供了 IService 接口,该接口对应 Service 层。MyBatis Plus 的通用 Service CRUD 实现了 IService 接口,进一步封装 CRUD

该接口使用 get(查询单行)、remove(删除)、list(查询集合)和 page(分页)前缀命名的方式进行区别。

    @Autowired
    OnlinePriceService onlinePriceService;
    @Test
    public void testService(){
        OnlinePrice price = new OnlinePrice();
        price.setId(22222222L);
        price.setDescription("test");
        onlinePriceService.save(price);
        QueryWrapper<OnlinePrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("description","test");
        OnlinePrice one = onlinePriceService.getOne(queryWrapper);
        Page<OnlinePrice> page = new Page<>(1,4);
        QueryWrapper<OnlinePrice> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.between("add_date", "2022-02-02", "2022-02-10");
        onlinePriceService.page(page,queryWrapper1);
    }


以上介绍了mybatisplus的常用基础用法,mybatisplus还有自动代码生成等其他功能,可以自动生成代码,以后有空继续学习分享

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <!-- springboot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> <!-- mysql 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> ``` 2. 配置数据源 在 `application.properties` 文件中添加以下配置: ``` # 数据库连接配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root # mybatis-plus 配置 mybatis-plus.configuration.map-underscore-to-camel-case=true ``` 3. 创建实体类 ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 4. 创建 Mapper 接口 ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 配置 Mapper 扫描 在启动类上添加注解 `@MapperScan("com.example.demo.mapper")`,用于扫描 Mapper 接口。 ```java @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 6. 测试 在 Controller 中注入 `UserMapper`,并进行测试。 ```java @RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/user") public List<User> getUserList() { return userMapper.selectList(null); } } ``` 以上就是 Spring Boot 整合 MyBatis-Plus 的基本配置和使用方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值