mybatis study notes (3) dynamic SQL

MyBatis's dynamic SQL is based on OGNL expressions, which can help us easily implement some logic in SQL statements. The main tags are if choose (when, otherwise) trim where set foreach (1) if is a simple conditional judgment statement such as the following code














<select id="queryIFTest"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person where 1=1
      <if test="name!=null">
         and name=#{name}
      </if>
       <if test="sex!=null">
         and sex=#{sex}
      </if>
      <if test="age!=null">
         and age>=#{age}
      </if>
    </select>



(2) The above code finds that because the condition of 1=1 is added to the splicing condition, it can be used more flexibly by changing a label. The function of the where statement is to simplify the judgment of the conditions in where in the SQL statement. You can intelligently remove and or or in the condition. For example, the following code

<select id="queryWhereTest"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person
      
      <where>
      <if test="name!=null">
          name=#{name}
      </if>
       <if test="sex!=null">
         and sex=#{sex}
      </if>
      <if test="age!=null">
         and age>=#{age}
      </if>
      
      </where>
    </select>



(3)
The role of the choose element is equivalent to the switch statement in JAVA, which is basically the same as the role and usage of choose in JSTL. Only one of the conditions is selected for execution, which is usually matched with when and otherwise. Consider the following example:

<select id="queryChooseTest"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person where 1=1
      
      <choose>
      <when test="name!=null">
         and name=#{name}
      </when>
       <when test="sex!=null">
         and sex=#{sex}
      </when>
      <when test="age!=null">
         and age=#{age}
      </when>
      
      </choose>
    </select>



(4) The trim mark is a format mark, which can more flexibly remove the labels of redundant keywords, and complete the functions of where and set with other marks. Prefix When the

prefix 
has suffix and the suffix has  
prefixOverrides, the front  
suffixOverrides are automatically judged, and the rear is automatically judged.
See Let's make it clearer with an example.

<select id="queryTrimTest"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person
      
      <trim prefix="where" prefixOverrides="and |or">
      <if test="name!=null">
          name=#{name}
      </if>
       <if test="sex!=null">
         or sex=#{sex}
      </if>
      <if test="age!=null">
         and age>=#{age}
      </if>
      
      </trim>
    </select>



The meaning of the above code is: when WHERE is followed by AND or OR, remove AND or OR. In addition to WHERE, there is actually a more classic implementation, that is SET.
(5) The set element is mainly used in update operations. Its main function is similar to that of the where element, mainly to output a set before the contained statement, and then if the contained statement ends with a comma, it will put the The comma is ignored, and an error occurs if the set contains empty content. With the set element we can dynamically update the modified fields. Here is a sample code:







<update id="testSetPerson" parameterType="com.lql.study.model.Person" >
        update person
        <set>
        <if test="name!=null">
          name=#{name},
       </if>
       <if test="sex!=null">
         sex=#{sex},
      </if>
      <if test="age!=null">
         age>=#{age},
       </if>
       <if test="remark!=null">
         remark>=#{remark},
       </if>
        </set>
        
        where pid=#{pid}
        
    </update>
    




(6)
foreach is mainly used in the construction of in conditions, it can iterate a collection in the SQL statement. The attributes of the foreach element mainly include item, index, collection, open, separator, and close. item represents the alias of each element in the collection when iterating, index specifies a name, which is used to represent the position of each iteration during the iteration process, open represents what the statement starts with, and separator represents between each iteration What symbol is used as a delimiter, close means what to end with, the most critical and error-prone when using foreach is the collection attribute, which must be specified, but in different cases, the value of this attribute is different. , there are mainly three cases:
if a single parameter is passed in and the parameter type is a List, the collection attribute value is list
. If a single parameter is passed in and the parameter type is an array array, the collection attribute The value is array
. If the incoming parameters are multiple, we need to encapsulate them into a Map. Of course, a single parameter can also be encapsulated into a map. In fact, if you pass in parameters, it will also be in MyBatis. It is encapsulated into a Map, and the key of the map is the parameter name, so at this time the value of the collection attribute is the key of the incoming List or array object in the encapsulated map.

Look at the following two examples, one is a single parameter, the other is a multi-parameter example

1. Single parameter
<select id="queryForeachTest"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person where age in
      <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
    </select>


public void queryForeachTest(List<Integer>ages) 
	{
		SqlSession session = sessionFactory.openSession();
		 IPersonOption op=session.getMapper(IPersonOption.class);
		 List<Person> ps=op.queryForeachTest(ages);
		 if(ps.size()>0)
		 {
			 for(int i=0;i<ps.size();i++)
			 {
				 System.out.println(ps.get(i).getName()+","+ps.get(i).getSex()+" ,"+ps.get(i).getAge());
			 }
		 }
		 session.close();
	}

2.多参数
 <select id="queryForeachTest2"  parameterType="com.lql.study.model.Person" resultMap="resultListPerson">
      select * from  person where sex=#{sex} and age in
      <foreach collection="ages" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
    </select>



1) Implementation method


public void queryForeachTest2(Map<String, Object> params)
	{
		SqlSession session = sessionFactory.openSession();
		 IPersonOption op = session.getMapper (IPersonOption.class);
		 
		 List<Person> ps=op.queryForeachTest2(params);
		 if(ps.size()>0)
		 {
			 for(int i=0;i<ps.size();i++)
			 {
				 System.out.println(ps.get(i).getName()+","+ps.get(i).getSex()+" ,"+ps.get(i).getAge());
			 }
		 }
		 session.close();
	}


2) calling code
ArrayList<Integer> ages=new ArrayList <Integer>();
			ages.add(35);
			ages.add(18);
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("ages", ages);
			 params.put("sex", "女");
			 test.queryForeachTest2(params);
			 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326923543&siteId=291194637