MyBatis:动态SQL高级标签使用方法指南

MyBatis 中动态 SQL 标签 在 MyBatis 中,动态 SQL 是构建灵活且高效的 SQL 语句的重要工具。通过使用动态 SQL 标签,开发者可以根据不同的条件动态生成 SQL 语句的各个部分,从而避免手动拼接字符串带来的复杂性和潜在的错误。 阅读详情
AI摘要

本文介绍MyBatis动态SQL高级标签使用方法。先阐述使用动态SQL的业务场景,接着说明Springboot项目中SQL映射方式,包括XML映射文件和注解映射。重点介绍动态SQL执行原理及常用核心标签用途与示例,还提及使用注意事项和最佳实践,能提高SQL代码可维护性和安全性。

一、引言

目前互联网大厂在搭建后端Java服务时,常使用Springboot搭配Mybatis/Mybatis-plus的框架。Mybatis/Mybatis-plus之所以能成为当前国内主流的持久层框架,与其本身的优点有关:支持定制动态 SQL、存储过程及高级映射,简化数据库操作。

可能有人会问, 为什么要用动态SQL,在开发过程中把SQL写死不是比较方便、更加不容易出错吗?其实这是由开发过程中具体业务需求决定的,比如在用户注册场景下,用户注册填写信息时,会有必填字段和非必填字段,不同用户注册时传给后端的参数有区别,对应的插入用户表的SQL也不一样,因此,在这些的场景下开发人员需要使用动态SQL来完成。本文首先介绍Springboot项目中SQL映射方式,最后介绍动态SQL和支持动态SQL的核心标签。

欢迎关注工 众号:ItBeeCoder,查看更多高质量技术文章,发送“后端”获取资料

二、SQL映射方式

1、XML映射文件,该文件通常位于 resources/自定义的包路径/mapper 目录。

示例:

  <!-- UserMapper.xml -->
  <mapper namespace="com.example.UserMapper">
    <select id="selectUserById" resultType="User">
      SELECT * FROM user WHERE id = #{id}
    </select>
  </mapper>

2、注解映射

适用场景:简单 SQL 可直接在接口方法上使用注解。

示例:

public interface UserMapper {
   
   
    @Insert("INSERT INTO user(name) VALUES(#{name})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUser(User user);
  }

欢迎关注工 众号:ItBeeCoder,查看更多高质量技术文章,发送“后端”获取资料

三、动态SQL及常用标签

在 MyBatis中,动态SQL允许开发人员根据不同的条件构建不同的 SQL 语句。执行原理为,使用OGNL从SQL参数对象中计算表达式的值,根据表达式的值动态拼接SQL,以此来完成动态SQL的功能。动态SQL中常用的核心标签有:、、、、、等。

1、动态 SQL

  • 以下SQL为XML文件中复杂动态SQL的示例:
  <select id="searchUsers" resultType="User">
    SELECT * FROM user
    <where>
      <if test="name != null">
         AND name LIKE CONCAT('%', #{name}, '%')
      </if>
      <if test="roles != null">
        AND role IN
        <foreach item="role" collection="roles" open="(" separator="," close=")">
          #{role}
        <
MyBatis实现动态SQL赋能技术更新 物理射线检测 阅读详情

相关推荐

Spring Boot整合MyBatis-Plus之动态SQL——MyBatis编程的精髓

通过以上的代码示例,我们详细介绍了在Spring Boot项目中如何整合MyBatis-Plus,并重点讨论了MyBatis最拿得出手的功能之一——动态SQL。通过使用动态SQL,我们可以根据不同的条件生成不同的SQL语句,从而实现灵活的查询操作。而在Java领域,MyBatis是一个广泛使用的持久化框架,它提供了强大的SQL映射能力和灵活的查询方式。MyBatis通过提供一些特殊的标签和方法来支持动态SQL,这使得我们可以根据不同的情况生成不同的SQL语句,避免了硬编码和大量的if-else语句。

TechChamp的博客 588

MyBatis:动态 SQL 标签

MyBatis动态SQL标签介绍

啊Q老师 7633

Mac新手必看:nvm安装全攻略(含常见错误解决方案)

本文为Mac开发者提供nvm安装与使用全攻略,涵盖环境准备、安装步骤、Shell配置优化及常见错误解决方案。详细讲解如何利用nvm管理多Node版本,提升开发效率,特别针对国内用户提供网络问题解决技巧,是Mac新手必备的Node版本管理指南。

weixin_28839699的博客 1643

大疆航线文件解析指南:5分钟搞懂KMZ里的template.kml和waylines.wpml区别

本文深入解析大疆无人机航线文件KMZ中template.kml与waylines.wpml的核心区别。template.kml是定义任务框架和全局参数的可编辑模板,而waylines.wpml是包含精确执行指令的最终文件。理解两者差异对于高效规划航线、批量生成任务及进行二次开发至关重要。

sun99的博客 875

《C语言小游戏之贪吃蛇程序代码》

//为广大编程游戏爱好者提供一个参考的游戏源代码#include&lt;stdio.h&gt;#include&lt;conio.h&gt;#include&lt;windows.h&gt;#include&lt;time.h&gt;#define framex 5#define framey 5#define wide 20#define high 20int i,j,a[2];//将光标移动到...

qq_42052821的博客 2万+

深度强化学习中的动作屏蔽(Action Masking)

在复杂环境中使用动作屏蔽,实现更好的训练效果

Kiek17的博客 5888

VMware Workstation 17 Pro 保姆级教程:手把手教你安装银河麒麟 Kylin V10 SP3 国产系统

本文提供VMware Workstation 17 Pro安装银河麒麟Kylin V10 SP3的详细教程,涵盖环境准备、虚拟机配置、系统安装及优化全流程。通过分步指导和实用技巧,帮助用户高效搭建国产操作系统开发测试环境,特别适合技术自主可控需求场景下的虚拟化实践。

weixin_30879169的博客 653

华为 MetaERP 通过元数据驱动的多组织架构 + 内部交易协同 + 自动对账引擎 + 合并规则引擎,实现多组织内部往来与合并报表的全流程自动抵消,核心是源头标准化、过程自动化、结果可追溯

摘要: 华为MetaERP通过元数据驱动的多组织架构与主数据标准化,实现内部往来与合并报表全流程自动化。其核心包括:统一组织模型与主数据(确保数据口径一致)、内部交易协同(自动生成对称凭证)、智能对账引擎(多维度自动匹配差异)、合并规则引擎(配置化抵消模板)。依托GaussDB高性能数据库与流批一体架构,华为全球88家子公司合并报表效率提升400%,关账时间缩短至2小时,支持多准则、多币种自动抵消,审计全程可追溯。相比传统ERP,MetaERP在协同性、自动化与扩展性上优势显著,为跨国集团提供高效、准确的合

金牌架构师 267

分布式计算Ray框架面试题及参考答案

动态任务图执行引擎是一种能够根据任务之间的依赖关系和运行时的实际情况,动态构建和执行任务图的系统。在 Ray 中,动态任务图执行引擎允许任务在运行时根据数据可用性、计算资源状态等因素,灵活地决定后续任务的执行顺序和方式。对于 AI 应用来说,其往往具有动态性的特点。例如,在深度学习模型的训练过程中,可能需要根据训练的结果动态调整下一轮训练的参数、数据增强方式或者模型结构。动态任务图执行引擎可以很好地支持这些动态需求。它能够根据 AI 应用中各个任务的实时输出和依赖关系,动态地生成和调整任务图。

大模型大数据攻城狮的专栏 1356

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度学习工具包 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")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

IMSL CNL 7.0.0 (x86-64)Crack

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

上一篇: Linux系统常用命令用法详解
下一篇: MySQL:一文带你掌握数据库日期时间函数及用法
It_BeeCoder
博客等级 码龄10年 967粉丝 238原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址