7. Dynamic Sql statement

1, dynamic SQL: if statements

We can see that if # {name} is empty, then the query result is empty, how to solve this problem? Use to determine if

 1 <select id="selectByWhere1" resultType="com.zhiyou100.wc.bean.Users">
 2           select 
 3           <include refid="usercolumns"></include>
 4           from users 
 5           <if test="name!=null ">
 6                where name=#{name}
 7           </if>
 8           <if test="sex!=null and sex!=''">
 9               and sex=#{sex}
10           </if>   
11     </select>

  Write we can see that if sex is equal to null, then the query to select * from users where name = # {name}, but if the name is empty it? Then the query to select * from users where and sex = # {sex}, this is wrong SQL statement, how to solve it? Consider the following statement where

2, dynamic SQL: if + where statements

1  ! <- solve: if the second condition is met, the first condition is not met. So that led sql statement error. 
2          IF + where: if a condition where the first and removes and
 . 3       -> 
. 4      < SELECT ID = "selectByWhere2" the resultType = "com.zhiyou100.wc.bean.Users" > 
. 5            SELECT 
 . 6            < the include the refid = "usercolumns " > </ the include > 
. 7            from Users 
 . 8            < WHERE > 
. 9                < IF Test =" name! = null " >
                if>
12               <if test="sex!=null and sex!=''">
13                   and sex=#{sex}
14               </if>   
15           </where>
16     </select>

The "where" label will know if it contains the tag has a return value, then it is inserted into a 'where'. In addition, if the label is returned content AND or OR the beginning, it will weed out

3, dynamic SQL: if + set statement

Similarly, for SQL query statement contains the keywords where, if during the time of the update operation, the set contains keywords, how we deal with on top of it?

. 1  <-! IF SET +
 2          If the transmitted field is null, then retain the original content
 . 3       -> 
. 4      < Update ID = "the updateUser" the parameterType = "com.zhiyou100.wc.bean.Users" > 
. 5          Update Users 
 . 6          < SET > 
. 7              < IF Test = "name! = null" > 
. 8              name = # {name},
 . 9              </ IF > 
10              < IF Test = "Sex! = null" > 
. 11              Sex = # {Sex},
 12              </if>
13             <if test="age!=0">
14             age=#{age},
15             </if>
16         </set>
17         where id=#{id}
18     </update>

4, dynamic SQL: choose (when, otherwise) statement

Sometimes, we do not want to use all of the query, just select one of them, a query can be satisfied, the label may choose to use to solve such problems, similar to Java's switch statement

 1 <!-- choose+when+otherwise -->
 2     <select id="selectByWhere3" resultType="com.zhiyou100.wc.bean.Users">
 3           select 
 4           <include refid="usercolumns"/>
 5           from users 
 6           <where>
 7               <choose>
 8                   <when test="name!=null ">
 9                         name like concat('%',#{name},'%')
10                   </when>
11                   <when test="sex!=null and sex!=''">
12                       sex=#{sex}
13                   </when>
14                   <otherwise>
15                       age>=#{age}
16                   </otherwise>
17              </choose>    
18           </where>
19     </select>

In other words, here we have three conditions, id, name, sex, you can select only one as a query

    If id is not empty, then the query is: select * from users where id =?

    If id is empty, then see if the name is empty, if not empty, then the statement select * from users where name = ?;

          If the name is empty, then the query to select * from users where sex =?

 

5, dynamic SQL: trim statements

  a trim flag is formatted marker, or may fulfill the functions set where labeled

  ①, with trim rewritten if + where the second point above statement

. 1  <-! TRIM -> 
2      < SELECT ID = "selectByWhere4" the resultType = "com.zhiyou100.wc.bean.Users" > 
. 3            SELECT 
 . 4              < the include the refid = "usercolumns" /> 
. 5            from Users 
 . 6            <! - -  
. 7              prefix: the trim before adding the string returned in a set
 . 8              prefixOverrides: trim override prefix string is returned and | or
 . 9              suffix: adding a set trim string returned after
 10              suffixOverrides: trim covering suffix string returned
 . 11           -> 
12            <trim prefix="where" prefixOverrides="and / or">
13               <if test="name!=null ">
14                     name=#{name}
15               </if>
16               <if test="sex!=null and sex!=''">
17                   and sex=#{sex}
18               </if>   
19           </trim>
20     </select>

②, rewrite the third point above statement with trim if + set

. 1  <-! Trim -> 
2      < Update ID = "updateUser2" the parameterType = "com.zhiyou100.wc.bean.Users" > 
. 3          Update Users 
 . 4          <-!  
. 5              prefix: the front trim string returned Add a SET
 . 6              prefixOverrides: trim override prefix string is returned and | or
 . 7              suffix: added after the string is returned in a trim SET
 . 8              suffixOverrides: trim cover suffix string returned
 . 9           -> 
10          < TRIM prefix = "SET" suffixOverrides = "," > 
. 11              <if test="name!=null">
12             name=#{name},
13             </if>
14             <if test="sex!=null">
15             sex=#{sex},
16             </if>
17             <if test="age!=0">
18             age=#{age},
19             </if>
20         </trim>
21         where id=#{id}
22     </update>

6, dynamic SQL: SQL fragment

Sometimes be a particularly large number of sql statements that we use in order to increase the reusability of the code, simplify the code, we need these codes extracted, then call when using

1     <sql id="usercolumns">
2         id,name,age,sex
3     </sql>

Sql fragment references

 1 <select id="selectByWhere1" resultType="com.zhiyou100.wc.bean.Users">
 2           select 
 3           <include refid="usercolumns"></include>
 4           from users 
 5           <if test="name!=null ">
 6                where name=#{name}
 7           </if>
 8           <if test="sex!=null and sex!=''">
 9               and sex=#{sex}
10           </if>   
11     </select>

Note: ①, is preferably defined based on a single table sql fragments, fragments improve reusability

     ②, the fragments do not include sql where 

 

7, dynamic SQL: foreach statement

 Requirements: We need to query the user table user id, respectively, 2, 3

  sql语句:delete from users where id=1 or id=2 or id=3

       delete from users where id in (1,2,3)

1, we use foreach to rewrite delete from users where id in (1,2,3)

. 1  <-! Delete by the foreach -> 
2       < Delete ID = "deleteByIds" > 
. 3          Delete Users from WHERE ID in
 . 4          <-! 
. 5                  Collection: Specifies the attributes set in the input object
 . 6                  Item: each iteration generated object
 . 7                  Open: splicing string of the traversing
 . 8                  Close: splicing at the end of the string
 . 9                  Separator: the splice between the need to traverse the object string
 10                -> 
. 11          < the foreach Collection = "IDS" Open = "(" Close = ")" Separator = "," item="id">
12             #{id}
13         </foreach>
14         
15     </delete>

2, we use foreach to rewrite delete from users where id = 1 or id = 2 or id = 3

. 1  < Delete ID = "deleteByIds2" > 
2          Delete from Users  
 . 3          <-! 
. 4              Collection: Specifies the attributes set in the input object
 . 5              Item: traversing each generated object
 . 6              Open: splicing string of the traversing
 . 7              Close: splicing the end of the string
 . 8              Separator: the splice between the need to traverse the object string
 . 9              Delete Users from WHERE ID = = 2. 1 or ID or ID. 3 =
 10            -> 
. 11          < the foreach Collection = "Ids2" Open = "WHERE " Separator =" or " Item =" the above mentioned id " >
12             id=#{id}
13         </foreach>
14         
15     </delete>

test:

 1 /**
 2      * delete in()
 3      */
 4     @Test
 5     void testdeleteByIds() {
 6         List<Integer> ids=new ArrayList<>();
 7         ids.add(7);
 8         ids.add(8);
 9         usersDao.deleteByIds(ids);
10     }
11     /**
12      * delete or
13      */
14     @Test
15     void testdeleteByIds2() {
16         List<Integer> ids2=new ArrayList<>();
17         ids2.add(6);
18         ids2.add(9);
19         usersDao.deleteByIds2(ids2);
20     }

 3. Fuzzy query

1.UsersMapper.xml

 1 <!-- choose+when+otherwise  模糊查询 -->
 2     <select id="selectByWhere3" resultType="com.zhiyou100.wc.bean.Users">
 3           select 
 4           <include refid="usercolumns"/>
 5           from users 
 6           <where>
 7               <choose>
 8                   <when test="name!=null ">
 9                         name like concat('%',#{name},'%')
10                   </when>
11                   <when test="sex!=null and sex!=''">
12                       sex=#{sex}
13                   </when>
14                   <otherwise>
15                       age>=#{age}
16                   </otherwise>
17              </choose>    
18           </where>
19     </select>

2.Usersdao

1 public List<Users> selectByWhere3(Users users); 

3. Test

 1     /**
 2      * 模糊查询
 3      */
 4     @Test
 5     void testSelectByWhere3() {
 6         Users users= new Users();
 7         users.setName("晨");
 8         users.setSex("男");
 9         List<Users> list=usersDao.selectByWhere3(users);
10         System.out.println(list);
11     }

 

Guess you like

Origin www.cnblogs.com/banzhuanlaowang/p/11455354.html