MyBatis SQL fragments in dynamic SQL

Source: Internet
Author: User

Using SQL fragments in MyBatis can improve the reusability of code, as in the following scenarios:

1. Create Dynamic SQL

<sql id= "Sql_count" >select count (*) </sql>

1. function

<select id= "Selectlistcountbyparam" parametertype= "map" resulttype= "String" >

<include refid= "Sql_count"/> from table_name

</select>

3. Analysis

Use the include tag to reference the SQL fragment ID when using the SQL fragment, and the ID of the SQL fragment must be unique in the current space

    Of course, the SQL fragment can also write other content, as long as the syntax is consistent with the specification is possible. As follows:
<sql id= "Sql_where" >
<trim prefix= "WHERE" prefixoverride= "and | OR ">
<IF test= "id! = NULL" >and id=#{id}</if>
<if test= "Name! = null and Name.length () >0" >and name=#{name}</if>
<if test= "Gender! = null and Gender.length () >0" >and gender=#{gender}</if>
</trim>
</sql>


<select id= "Updatebykey" parametertype= "Map" resulttype= "List" >
SELECT * FROM user
<include refid= "Sql_where" >
</select>

MyBatis SQL fragments in 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.