MyBatisPlus自定义sql

mybatis写自定义sql(一) 在这个例子中,我们使用了MyBatis的`@Select`注解来声明一个自定义查询。请注意,我们将查询参数包装在`${}`符号中,并使用`#{}`将它们映射到查询中的占位符。首先,在您的MyBatis映射文件中,您需要声明一个接口,该接口将描述您要执行的操作。在这个例子中,我们测试了`UserService`中的`getUsersByName()`方法,并检查是否返回了正确数量的用户。2. 创建一个数据库表和实体类。在这个例子中,我们将使用一个名为`user`的表,它有两个列:`id`和`name`。 阅读详情
AI摘要

本文详细介绍了MyBatisPlus中自定义SQL的多种方法,包括使用注解、标签以及条件构造器等。同时,深入探讨了{}和${}在SQL中的不同应用及其安全性和效率问题。此外,还涉及了如何使用第三方工具进行多表查询和分页,以及在实际操作中遇到的问题和解决方案。

MyBatisPlus自定义sql

在说怎么实现之前我们要先明白一个概念,就是mybatis-plus是在mybatis的基础上进行增强,并不做改变,所以mybatis的操作在mybatis-plus中也是一样可以使用的,咱们直接上代码.

1、单纯地使用注解自定义SQL

image-20230715121432056

image-20230715121542720

image-20230715121549283

image-20230715121556142

image-20230715121601683

image-20230715121609607

image-20230715121616776

image-20230715121624576

数据库数据:

image-20230715121653508

执行测试方法后结果如下:

image-20230715121730509

注意:这里我们把MybatisPlusConfig这个类注释掉,持久层的类使用@Mapper注解,也是一样可以运行的哈。

image-20230715121811876

image-20230715121940139

结果:

image-20230715122039249

2、使用注解加标签做自定义sql

展示1:使用if标签

image-20230715134039362

image-20230715134358902

image-20230715134349472

image-20230715134415320

结果:

image-20230715134546780

展示2:使用foreach标签

image-20230715140024541

image-20230715140133377

image-20230715140144203

image-20230715140154121

结果:

image-20230715140255069

展示3:使用foreach标签

下面我们使用id来查找一下:

image-20230715141029044

image-20230715141056024

image-20230715141108839

image-20230715141122343

结果:

image-20230715141149419

扩展知识点:{} 和 ${} 的区别?

一、区别概述
1.1、主要区别:

1、#{} 是预编译处理,${} 是直接替换;

2、${} 存在SQL注入的问题,而 #{} 不存在;

Ps:这也是面试主要考察的部分~

1.2、细节上:

1、${} 可以实现排序查询,#{} 不能实现排序查询。

2、${} 可以直接进行模糊查询(但不建议,存在 SQL 注入问题),#{} 不可以直接进行模糊查询,但可以通过 mysql 内置函数 concat() 实现模糊查询(不存在 SQL 注入问题)。

二、具体描述
2.1、预编辑处理 vs 直接替换

预编辑处理:是指 MyBatis 在处理 #{} 时,就是把 #{} 替换成了 ?号,使用 PreparedStatement 的 set 方法来赋值。也就是说 #{} 会把 {} 内的整体看成 value ,最后再给 value 加上单引号,重点强调引号内部是一个整体( #{} 不会发生 SQL 注入的根本原因)。

直接替换:是指 MyBatis 在处理 ${} 时,会把 ${} 替换成变量的值(不会加引号处理)。

2.2、SQL 注入问题
2.2.1、引发 SQL 注入

例如现在有一个登陆程序,需要输入正确的账户和密码才能登录,当使用了 SQL 注入就可以在不知道密码的情况下进行登录,如下

xml 文件如下:

    <select id="login" resultType="com.example.demo.entity.Userinfo">
        select * from userinfo where username = '${username}' and password = '${password}'
    </select>

接口如下:

    /**
     * 登录逻辑
     * @param username
     * @param password
     * @return
     */
    Userinfo login(@Param("username") String username,
                   @Param("password") String password);

测试方法如下:

    @Test
    void login() {
   
   
        String username = "admin";
        String password = "' or 1 = '1";
        Userinfo userinfo = userMapper.login(username, password);
        System.out.println("登录状态:" + (userinfo == null ? "失败" : "成功"));
    }

执行结果如下:

image-20230715141958720

2.2.2、SQL 注入分析

可以在运行结果的日志中看到,我们最后执行的SQL语句如下:

image-20230715142046172

在 MySQL 中 1 = ‘1’ 结果必然为 true,所以不难分析出,如上 SQL 一定会将这张表中的用户全部返回(即使账号都填写错了,照样返回,因为1 = ‘1’ 必然为 true );

使用 ${} 的注意事项:一定是可以穷举的值,在使用之前一定要对传递的值进行合法性验证(在Controller中通过穷举的方式验证安全性)。

2.3、排序查询

使用 ${} 可以实现排序查询,而 #{} 不可以实现排序查询,因为使用 #{} 查询时,如果传递的值为 String 就会加单引号,导致 sql 错误。

例如你期望的 sql 语句为:select * from userinfo order by id desc;

而 #{sort} 中传入的是一个 String 类型的值为 “desc”;

那么最终实际的 sql 语句为:select * from userinfo order by id ‘desc’;这必然是错误的~

2.4、like 查询
2.4.1、${} 模糊查询
方式一:直接替换 
<select id="likeSelect" resultType="com.example.demo.entity.Userinfo">
    select * from userinfo where username like '%${key}%'
</select>
 
 
方式二:使用concat进行字符串拼接
<select id="likeSelect" resultType="com.example.demo.entity.Userinfo">
    select * from userinfo where username like concat('%', '${key}', '%')
</select>

Ps:虽然可以这样,但并不建议使用 ${} 进行模糊查询,因为存在 SQL 注入问题。

2.4.2、#{} 模糊查询
<select id="likeSelect" resultType="com.example.demo.entity.Userinfo">    
    select * from userinfo where username like concat('%', #{key}, '%')
</select>
2.4.3、#{} 模糊查询问题分析

你期望的 sql 语句:select * from user where username = ‘%abc%’;

然而当你使用 #{} 传入的参数会自带引号,于是就变成了:select * from user where username = ‘%’ abc ‘%’;

注意:

注意一点:接口里面的形参如果没有使用@Param注解,那么你sql里面就不能直接用${}

image-20230715145409957
1)使用@Param注解
 
当以下面的方式进行写SQL语句时:
 
    
mybatisplus/mybatis自定义sql语句-源码下载 MybatisPlus通过BaseMapper为我们带来了丰富的基础功能操作,非常使用。但是在实际的操作中,我们还需要大量的自定义SQL的的时候,这时候就需要自定义xml,从而自定义sql语句。 阅读详情

相关推荐

MyBatis-plus执行自定义SQL

还有另外24篇MySQL+MyBatis+MyBatis-plus相关文章。

lydms的博客 9539

Spring Boot入门(14):使用Mybatis-Plus轻松实现高效自定义SQL操作!

如何使用Mybatis-Plus执行自定义SQL,一文教会你。

**My Coding Family** 3万+

使用MyBatisPlus实现自定义SQL分页功能

大家好,我是Leo哥🫣🫣🫣,今天给大家带来关于精品SpringBoot专栏,暂且就给他起名为循序渐进学SpringBoot,这里我参考了我上一个专栏:循序渐进学SpringSecurity6。有需要的朋友可以抓紧学习来哈,带你从SpringSecurity从零到实战项目。

分享思想,留下痕迹。 1504

MyBatisPlus快速入门(七)自定义SQL

自定义 SQL 是指在使用 Mybatis-Plus 时,可以通过注解或XML配置文件编写自己的SQL语句,以满足个性化的查询需求。使用自定义 SQL 可以方便地实现复杂的查询逻辑,包括多表联合查询、分页查询、动态条件查询等。

Designer 小郑的技术博客 2437

FDTD Script命令学习-farfield3d/farfieldux/farfielduy

介绍了farfield3d/farfieldux/farfielduy命令功能,及不同应用语法和参数介绍,以及对官网示例进行介绍。

jxxl_1314的博客 3106

利用随机矩阵理论(random matrix theory)确定微生物网络构建阈值

利用随机矩阵理论(random matrix theory)确定微生物网络构建阈值

微生物生态学分析 7654

头歌操作系统 课堂练习4.3:段页式内存管理 答案 无解析

头歌操作系统 课堂练习4.3:段页式内存管理 答案 无解析

kercii的博客 8234

Python实战:5分钟搞定固定翼无人机三自由度仿真(附完整代码)

本文提供了一个基于Python的固定翼无人机三自由度仿真快速实现方案。通过面向对象设计,封装了核心运动学模型,并对比了欧拉法与龙格-库塔法两种积分方法。文章附有完整实例代码,帮助算法工程师和研究人员在5分钟内搭建轻量级仿真环境,用于快速验证控制律、路径规划等核心算法逻辑。

docker7nomad的博客 753

【升级U8+】不能将值 NULL 插入列 ‘VT_ID‘,表 ‘VoucherItems‘;列不允许有 Null 值。

不能将值 NULL 插入列 ‘VT_ID’,表 ‘UFDATA_006_2012.dbo.VoucherItems’;列不允许有 Null 值。INSERT 失败。

努力不懈的为广大客户提供优质的产品与真诚、贴心、专业的服务! 522

Anaconda数据报错:Fatal error in launcher: Unable to create process using ‘“E:\Anaconda\python.exe“ “D:\

里面的pip.exe程序出现了问题,我这里直接删除,重新安装解决,上面已经手动删除pip.exe删除pip.exe,重新安装pip.exe用下面命令: 测试是否成功成功解决

Deng872347348的博客 1271

Qt视频播放器项目(打开文件,视频的播放与停止,进度条与视频进度绑定,调整音量,设置按钮图标,将槽函数与按钮绑定等功能)完整代码地址在末尾

【代码】Qt视频播放器项目。

分享计算机视觉,C++,网络摄像头研发,音视频开发,嵌入式等知识。 761

利用插件扩展 Qt 应用程序

不仅 Qt 本身可以通过插件进行扩展,而且 Qt 应用程序也可以通过插件来扩展,这需要应用程序使用 `QPluginLoader` 检测和加载插件。

青春不老,奋斗不止! 1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

上一篇: MyBatis-Plus之通用枚举
下一篇: mybatis映射文件相关的知识点总结
鲨鱼辣椒_TUT
博客等级 码龄5年 383粉丝 105原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值