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,提升自己的开发技能,快速构建高效、优雅的业务系统。

相关推荐
SamDeepThinking5 小时前
Java微服务练习方式
java·后端·微服务
米丘3 天前
微前端之 Web Components 完全指南
微服务·html
霸道流氓气质6 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
慧一居士6 天前
Feign的GET请求如何传递对象参数?
java·spring cloud
敲个大西瓜6 天前
mybatis拦截器插件实现数据库字段加解密
mybatis
我登哥MVP6 天前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven
武子康6 天前
Java-28 深入浅出 Spring 实现简易Ioc-04 在上节的业务下手动实现AOP
java·后端·mybatis
慧一居士6 天前
SpringCloud 微服务Feigin 用的完整调用端和被调用的示例
java·spring cloud
一条泥憨鱼6 天前
苍穹外卖【day6|微信登录与商品浏览功能】
后端·mybatis·苍穹外卖