The focus of Mabatis is to configure the input and output mappings through a flexible organization of tags to SQL.
1. Unified Maintenance of duplicate SQL extracts in Mapper.xml, and foreach usage
usermappercustom.xml
<?xml version= "1.0" encoding= "UTF-8"? ><!DOCTYPE mapperpublic"-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace= " Cn.itcast.mybatis.mapper.UserMapperCustom "> <!--define a SQL fragment and extract the duplicate SQL statements: Define query criteria to be defined in single table, SQL fragment reusability is highly recommended do not include where suggestions to define the query criteria in a single unit, generally to write the query conditions full --<sql id= "Query_user_where" > <!--if a conditional value is spliced--<iftest= "User!=null" > <ifTest= "User.username!=null and user.username!=" "> <!--user input condition values and then stitching--and username like'%${user.username}% ' </if> <ifTest= "User.sex!=null and user.sex!=" >and sex=#{user.sex}</if> <!--below to splice: and ID in (1,10,16) -<!--Traversal ID List collection: Receive collection properties in input parameters item: Defines an object name for Each loop open: SQL stitching when starting loop Close: SQL separator stitching at end of loop: SQL every two cycles in the middle -<foreach collection= "IDs" item= "id" open= "and ID in (" close= ")" separator= "," >#{id}</foreach> <!--thinking: How to stitch and (ID=1 or id=10 or id=16) to achieveSELECT * from USER WHERE sex = ' 1 ' and ID in (1,10,16)
-</if> </sql> <!--General Conditions query user--<select id= "finduserlist" parametertype= "Queryuservo"Resulttype= "User" >Select id,username,birthday,sex,address from user<!--where tags are related to the WHERE keyword, you can remove the first and the condition from the <where> <!--referencing a SQL fragment if the cross-mapper reference requires a front plus namespace--<include refid= "Query_user_where" ></include> </where> </select> < !--comprehensive criteria Query user records Summary-<select id= "Findusercount" parametertype= "Queryuservo" resulttype= "int" >Select COUNT (*) from user<!--where tags are related to the WHERE keyword, you can remove the first and the condition from the <where> <!--referencing a SQL fragment if the cross-mapper reference requires a front plus namespace--<include refid= "Query_user_where" ></include> </where> </select></map Per>
Usermappercustom.java
Public Interface usermappercustom { // Comprehensive condition query user information public throws Exception; // General conditions Query total user records public intthrows Exception;}
Mapper.xml in Dynamic SQL