The trim details of dynamic SQL in MyBatis

Source: Internet
Author: User

I. BACKGROUND

I used to use <where>, <update>, <if>, <foreach> tags for many, know there is <trim> this tag, but seldom to use, nor to understand it deeply, Until recently encountered a problem. The problem is this:

A SQL has three int query fields A, B, C, and the expression is:A=#{a} and (B=#{b} OR c=#{c}). Where A is required, B and C are not required (it is assumed that an incoming-1 indicates that the field does not participate in the query). Then the expression will have the following patterns:

    • A=#{a}
    • A=#{a} and B=#{b}
    • A=#{a} and C=#{c}
    • A=#{a} and (B=#{b} OR c=#{c})

After seeing this requirement, the logic is quite simple, but writing mapper SQL is not so easy (if you have one, please post the comments below). Consider the multi-layer <if>, <choose> and other tags, although it can also achieve this function, but too cumbersome. Is there a simpler way to achieve this? Yes! <trim>!!!

Two. function description and Usage

Online about <trim> not much, by looking at the source of MyBatis, a sentence to describe the function of Trim: clause end-to-end replacement .

Usage:

WHERE a = #{a}<trim prefix= "and (" prefixoverrides= "OR" suffix= ")" ><if test= "B! =-1" >or B = #{b}</if>< If test= "c! =-1" >or C = #{c}</if></trim>

  

The trim details of dynamic SQL in MyBatis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.