SpringCloud 系列教程:微服务的未来(二)Mybatis-Plus的条件构造器、自定义SQL、Service接口基本用法

本篇博客将深入探讨 MyBatis-Plus 的三个核心功能:条件构造器自定义 SQLService 接口的基本用法。通过对这些功能的学习和掌握,开发者能够更加高效地使用 MyBatis-Plus 进行业务开发。

目录

前言

条件构造器

?自定义SQL

?Service接口基本用法

总结


前言

在现代 Java 开发中,MyBatis-Plus(简称 MP)作为 MyBatis 的增强工具,已经成为了开发者提高开发效率的利器。它通过简化 MyBatis 的操作,提供了多种便捷的功能,如自动生成 SQL、内置条件构造器、分页查询等。与 MyBatis 相比,MyBatis-Plus 更加简洁和高效,尤其适用于快速开发场景。

本篇博客将深入探讨 MyBatis-Plus 的三个核心功能:条件构造器自定义 SQLService 接口的基本用法。通过对这些功能的学习和掌握,开发者能够更加高效地使用 MyBatis-Plus 进行业务开发。


条件构造器

MyBatisPlus支持各种复杂的where条件,可以满足日常开发的所有需求。

查询名字中带o的,存款大于等于1000猿的人的id、username、info、balance字段

复制代码
select id,username,info,balance from user where username like ? and balance >= ?

    @Test
    void testQueryUser() {
        //构造查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .select("id","username","info","balance")
                .like("username","o")
                .ge("balance",1000);
        //查询
        List<User> userList =  userMapper.selectList(wrapper);
        userList.forEach(System.out::println);
    }

更新用户名为jack的用户的余额为2000

复制代码
update user set balance = 2000 where username = "jack"

    @Test
    void testUpdateByQueryMapper() {
        //需要更新的数据
        User user = new User();
        user.setBalance(2000);
        //更新的条件

        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq("username","jack");
        //执行更新
        userMapper.update(user,wrapper);
    }

    @Test
    void testUpdateByQueryMapper() {
        //更新的条件
        UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
                .set("balance",20)
                .eq("username","Jack");
        //执行更新
        userMapper.update(null,wrapper);
    }

更新id为1,2,4的用户的余额,扣200

复制代码
update user set balance = balance - 200 where id in (1,2,4);

    @Test
    void testUpdateWrapper(){
        List<Long> ids = List.of(1L, 2L, 4L);
        UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
                .setSql("balance = balance - 200")
                .in("id",ids);
        userMapper.update(null,wrapper);
    }

查询表中username模糊匹配o和balance >= 100的user中id、username、info、balance。

复制代码
    @Test
    void testLambdaWrapper(){
        //构造查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .select(User::getId,User::getUsername,User::getInfo,User::getBalance)
                .like(User::getUsername,"o")
                .ge(User::getBalance,100);
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

条件构造器的用法:

  • QueryWrapper和LambdaQueryWrapper通常用来构建select、delete、update的where条件部分
  • UpdateWrapper和LambdaUpdateWrapper通常只有在set语句比较特殊才使用
  • 尽量使用LambdaQueryWrapper和LambdaUpdateWrapper避免硬编码

自定义SQL

我们可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,然后自己定义SQL语句中剩下的部分。

将id在指定范围内的用户(例如1,2,4)的余额扣减指定值。

复制代码
<update id = "updateBalanceByIds">

    update user set balance = balance - #{amount}
    where id in
    <foreach collection="ids" separator=",",item="id" open="(" close=")">
        #{id}
    </foreach>
</update>

我们可以利用MvBatis Plus的包装器来构建复杂的Where条件,然后自己定义SOL语句中剩下的部分。

(1)基于包装器构建其中条件

复制代码
        List<Long> ids = List.of(1L, 2L, 4L);
        //构建条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .in(User::getId,ids);
        //自定义SQL方法调用
        userMapper.updateBalanceByIds(wrapper,amount);

(2)在mapper方法参数中用Param注解声明wrapper变量名称,必须是ew

复制代码
void updateBalanceByIds(@Param("ew") LambdaQueryWrapper<User> wrapper,@Param("amount") int amount);

(3)自定义SQL,并使用Wrapper条件

复制代码
<update id="updateBalanceByIds">
    update user set balance = balance - #{amount} ${ew.customSqlSegment}
</update>

userMapper类

复制代码
package com.itheima.mp.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.itheima.mp.domain.po.User;
import org.apache.ibatis.annotations.Param;


public interface UserMapper extends BaseMapper<User> {

    void updateBalanceByIds(@Param(Constants.WRAPPER)LambdaQueryWrapper<User> wrapper, @Param("amount") int amount);
}

测试方法

复制代码
    @Test
    void testCustomSqlUpdate(){
        //更新条件
        List<Long> ids = List.of(1L, 2L, 4L);
        int amount = 200;
        //定义条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .in(User::getId,ids);
        //自定义方法
        userMapper.updateBalanceByIds(wrapper,amount);
    }

Service接口基本用法

自定义接口需要去继承IService接口,实现类需要继承ServiceImpl

IUserService接口

复制代码
package com.itheima.mp.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.itheima.mp.domain.po.User;
import org.springframework.stereotype.Service;


public interface IUserService extends IService<User> {
}

UserServiceImpl类

复制代码
package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}

测试类

复制代码
package com.itheima.mp.service;

import com.itheima.mp.domain.po.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.LocalDateTime;


@SpringBootTest
class IUserServiceTest {

    @Autowired
    private IUserService userService;

    @Test
    void testsaveUser(){
        User user = new User();
        user.setUsername("XiaoHong");
        user.setPassword("123456");
        user.setPhone("18688990982");
        user.setBalance(1500);
        user.setInfo("{"age": 23, "intro": "英文老师", "gender": "female"}");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userService.save(user);
    }

}

总结

通过本篇博客的讲解,开发者应该对 MyBatis-Plus 的三个核心功能有了一个清晰的认识:

  1. 条件构造器QueryWrapper)使得查询条件构建更加简洁,极大减少了编写 SQL 语句的复杂度。
  2. 自定义 SQL使得在复杂的业务需求下能够灵活应对,提供了更大的自由度。
  3. Service 接口基本用法 通过继承ServiceImpl,大大简化了 CRUD 操作的实现,提升了开发效率。

这些功能不仅能够帮助我们提高开发效率,还能够减少代码冗余,提升代码的可读性和维护性。在实际的开发中,MyBatis-Plus 提供的这些工具将是日常工作中的好帮手。

希望通过本篇博客,读者能够更好地理解 MyBatis-Plus,提升自己的开发技能,快速构建高效、优雅的业务系统。

相关推荐
stark张宇2 天前
微服务架构必备:Gin + gRPC + Consul + Nacos + GORM 打造用户服务
微服务·gin·grpc
阿里云云原生5 天前
MSE Nacos Prompt 管理:让 AI Agent 的核心配置真正可治理
微服务·云原生
阿里云云原生5 天前
阿里云微服务引擎 MSE 及 API 网关 2026 年 1 月产品动态
微服务
追风筝的人er5 天前
企业管理系统如何实现自定义首页与千人千面?RuoYi Office 给出了完整方案
vue.js·spring boot·spring cloud
麦聪聊数据5 天前
统一 Web SQL 平台如何收编企业内部的“野生数据看板”?
数据库·sql·低代码·微服务·架构
莫寒清6 天前
Mybatis的插件原理
面试·mybatis
云司科技codebuddy6 天前
技术支持过硬Trae核心代理
大数据·运维·python·微服务
莫寒清6 天前
MyBatis 中动态 SQL 的作用
面试·mybatis
吹晚风吧6 天前
实现一个mybatis插件,方便在开发中清楚的看出sql的执行及执行耗时
java·sql·mybatis
码云数智-大飞6 天前
像写 SQL 一样搜索:dbVisitor 如何用 MyBatis 范式颠覆 ElasticSearch 开发
sql·elasticsearch·mybatis