search
HomeJavajavaTutorialIn-depth explanation of Mybatis series (9)---powerful dynamic SQL

The previous article "Mybatis series in simple terms (8)---mapper mapping file configuration select, resultMap" briefly introduced the query of mybatis. So far, CRUD has been explained. This article will introduce the powerful dynamic SQL of mybatis.

So, here comes the question: What is dynamic SQL? What is the role of dynamic SQL?

With the traditional method of using JDBC, I believe that when you combine complex SQL statements, you need to splice them together. If you don't pay attention, even missing a space will lead to errors. The dynamic SQL function of Mybatis is designed to solve this problem. It can be combined into very flexible SQL statements through if, choose, when, otherwise, trim, where, set, and foreach tags, thus improving the efficiency of developers. Let’s feel the charm of Mybatis dynamic SQL:

1. if: You can judge, and so can I!

As a programmer, who doesn’t understand if! You can also use if in mybatis:

<select>
           select * from user where 
           <if>
               id=#{id}           </if>
            and deleteFlag=0;</select>


##The above example: If If the incoming id is not empty, then SQL will concatenate id = #{id}. I believe everyone can understand this just by looking at it, so I won’t go into detail.

Careful people will find a problem: "You are wrong! If the id you pass in is null, then your final SQL statement will become select * from user where and deleteFlag=0, There is something wrong with this statement! "

Yes, at this time, the where tag of mybatis will make its grand debut:

##2. where, with me, the SQL statement The splicing conditions are all in the clouds! Let’s transform the above example through where:

<select>
           select * from user 
           <where>
               <if>
                   id=#{id}               </if>
               and deleteFlag=0;           </where>
 </select>


Some people will ask: “What are you talking about? What the hell! Compared with the above, isn’t it just an extra where tag? Will this one also show select * from user where and deleteFlag=0? "

Indeed, on the surface, It's just an extra where tag, but in essence, mybatis processes it. When it encounters AND or OR, it knows how to deal with it. In fact, we can customize this processing rule through the trim tag.

3. trim : My territory, I decide! The where tag above can actually be represented by trim as follows:

<trim>
  ... 
</trim>

It means: When WHERE is followed by AND or then When ORing, remove AND or OR. In addition to WHERE, there is actually a more classic implementation, which is SET.

4. set: Trust me, you won’t make any mistakes!

<update>
           update user set 
           <if>
               name = #{name},           </if> 
           <if>
               password = #{password},           </if> 
           <if>
               age = #{age}           </if> 
           <where>
               <if>
                   id = #{id}               </if>
               and deleteFlag = 0;           </where></update>
The problem comes again: "If I only have name that is not null, then wouldn't this SQL become update set name = #{name}, where... .. ? The comma after your name will cause an error! "

Yes, at this time, we can use the set tag provided by mybatis. The following is modified through the set tag:

<update>
           update user        <set>
          <if>name = #{name},</if> 
             <if>password = #{password},</if> 
             <if>age = #{age},</if> 
        </set>
           <where>
               <if>
                   id = #{id}               </if>
               and deleteFlag = 0;           </where></update>

这个用trim 可表示为:

<trim>
  ...</trim>

WHERE是使用的 prefixOverrides(前缀), SET是使用的 suffixOverrides (后缀), 看明白了吧!

5. foreach:  你有for, 我有foreach, 不要以为就你才屌!

java中有for, 可通过for循环, 同样, mybatis中有foreach, 可通过它实现循环,循环的对象当然主要是java容器和数组。

<select>
  SELECT *
  FROM POST P
  WHERE ID in  <foreach>
        #{item}  </foreach></select>

将一个 List 实例或者数组作为参数对象传给 MyBatis,当这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。同样, 当循环的对象为map的时候,index其实就是map的key。

6. choose:  我选择了你,你选择了我!

Java中有switch,  mybatis有choose。

<select>
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’  <choose>
    <when>
      AND title like #{title}    </when>
    <when>
      AND author_name like #{author.name}    </when>
    <otherwise>
      AND featured = 1    </otherwise>
  </choose></select>

以上例子中: 当title和author都不为null的时候, 那么选择二选一(前者优先), 如果都为null, 那么就选择 otherwise中的, 如果tilte和author只有一个不为null, 那么就选择不为null的那个。

纵观mybatis的动态SQL, 强大而简单, 相信大家简单看一下就能使用了。

好啦,本次就写到这!下篇文章将结合mybatis的源码分析一次sql语句执行的整个过程。

 

 以上就是深入浅出Mybatis系列(九)---强大的动态SQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),