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