MyBatis Dynamic SQL

Source: Internet
Author: User
Tags cdata

MyBatis tags used by dynamic sql:

1:if judgment

2:where solving the problem of SQL statement stitching condition

Cases:

<select id= "Finduserbyid" resulttype= "User" >

SELECT * from user where

<where>

<IF test= "id! = NULL" >

Id=#{id}

</if>

and deleteflag=0;

</where>

</select>

If id = NULL then the SQL statement will be: select * from user where and and deleteflag=0, it is obvious that this is the wrong SQL statement. Add where note can be resolved, such as top <where></where> Remove above red section where

3:trim processing Splicing

2 problems can also be handled as such

<select id= "Finduserbyid" resulttype= "User" >

<trim prefix= "where" prefixoverrodes= "and | or" >

? SELECT * from user where ?

<IF test= "id! = NULL" >

Id=#{id}

</if>

and deleteflag=0;

</trim>

</select>

4:set

<update id= "UpdateUser" parametertype= "Com.domin.User" >

Update User Set

<set>

<if test= "Name! = NULL" >

name = #{name},

</if>

</set>

and Deleteflag = 0;

</where>

</update>

If name = NULL, the SQL statement is Update user set and Deleteflag = 0, which is an obvious error. Use <set></set> replace <set>

It can also be trim processing

5:foreach looping through a collection or array

<select id= "Selectuser" resulttype= "Domain.domin.User" >

SELECT *

From user

where ID in

<foreach item= "Item" index= "index" collection= "list"

Open= "(" separator= "," close= ")" >

#{item}

</foreach>

</select>

The corresponding SQL is as follows:

SELECT * from user where ID in (item1,item2 ...)

Item1,item2 ... Represents the value of #{item} each time

6:choose equivalent to Swich in Java

The format is as follows:

<choose>

<when>

Statement

</when>

<otherwise>

Statement

</otherwise>

</choose>

Problems encountered:

<! [Cdata[and shelve_at <= #{currenttimemillis,jdbctype=bigint} and #{currenttimemillis,jdbctype=bigint} < unshelve_at]]>//can't be written <!. [Cdata[and shelve_at <= #{currenttimemillis,jdbctype=bigint} < unshelve_at]]>










MyBatis Dynamic SQL

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.