mybatis from entry to the master (D) Dynamic SQL

mybatis from entry to the master (D) Dynamic SQL

A Dian Profile

  One of the powerful features Mybatis is dynamic SQL, it can dynamically splicing sql statement, reduce the workload of development.

  Mybatis dynamic sql following four types of tags

  1. if

  2. choose (when, otherwise)

  3. trim (where, set)

  4. foreach

 

 

Two Dian <if />

   <if /> tag corresponds to an if statement java language, by determining whether the preset condition to splice sql statement. Wherein the determination conditions described ongl expressions, such as e.method (args) calling the object method, e.property access object properties, ongl can refer to this blog

 

  DynamicSqlUserMapper.java

User selectUserByUserNameAndAge(@Param("userName") String userName, @Param("age") Integer age);

  DynamicSqlUserMapper.xml

    <select id="selectUserByUserNameAndAge" resultMap="BaseResultMap">
        select * from user 
        where user_name=#{userName}
        <if test="age != null">
            and age=#{age}
        </if>
    </select>

 

  DynamicSqlTests.java

    @Test
    public void ifTest(){
        // 测试if动态sql

        User user=dynamicSqlUserMapper.selectUserByUserNameAndAge("tim", null);
        Assert.assertTrue(user!= null);

        user=dynamicSqlUserMapper.selectUserByUserNameAndAge("tim", 999);
        Assert.assertTrue(user == null);
    }

 

  

Wed and <choose />

  <Choose /> similar to java in if ... else if ... else ... statement

 

  DynamicSqlUserMapper.java

List<User> selectUserLikeByChoose(@Param("userName") String userName, @Param("age") Integer age, @Param("country") String country);

  DynamicSqlUserMapper.xml

    <!-- 2. choose(when, otherwise) 类似于 if, else  -->
    <select id="selectUserLikeByChoose" resultMap="BaseResultMap">
        select * from user 
        where user_name like '${userName}'
        <choose>
            <when test="age != null">
                and age = #{age}
            </when>
            <when test="country != null ">
                 and country like '${country}'
            </when>
            <otherwise>
                and user_id &gt; 10
            </otherwise>
        </choose>
    </select>

 

  DynamicSqlTests.java

    @Test
     public  void chooseTest () {
         // Test choose dynamic SQL 
        List <the User> Users = dynamicSqlUserMapper.selectUserLikeByChoose ( "% T",. 11, null ); // Note that, like xx%, where% of control parameters into 
        sqlSession .commit (); 
        Assert.assertTrue (the Users =! null ); 
        Assert.assertTrue (users.size () == 1 ); 

        the Users = dynamicSqlUserMapper.selectUserLikeByChoose ( "% t", null , "% State"); // Note that, like xx%, where% of control parameters into 
        sqlSession.commit (); 
        Assert.assertTrue (Users =! null );
        Assert.assertTrue(users.size()>1);
        
    }

 

 

Four Dian <where />

   <Where /> tag within the tag is that when the condition is not satisfied, it will remove inappropriate sql keywords. Such as <where /> inside of a condition does not hold, then where keywords will not be added stitching, <where /> on the inside of the conditions is not satisfied, the second holds, the second condition in the sql remove the statement "and" keyword. <Where /> and <set /> actually <trim /> the particular implementation.

 

  DynamicSqlUserMapper.java

List<User> selectUserLikeByWhere(@Param("userName") String userName,  @Param("country") String country);

  DynamicSqlUserMapper.xml

    <!-- 3. trim(where, set) -->
    <select id="selectUserLikeByWhere" resultMap="BaseResultMap">
        select * from user 
        <where>
            <if test="userName !=null and userName.trim().length()>0">
                user_name like #{userName}
            </if>
            <if test="country !=null and country.trim().length()>0">
                and country like #{country}
            </if>
        </where>
    </select>

 

  DynamicSqlTests.java

    @Test
     public  void whereTest () {
         // use where elements 
        List <the User> Users = dynamicSqlUserMapper.selectUserLikeByWhere ( "% T", ""); // Country parameter spaces are filtered, select * from user WHERE user_name like ? 
        Assert.assertTrue (the Users =! null ); 
        Assert.assertTrue (users.size () > 1 ); 
        
        
        // ? the SELECT * from the User Country like the WHERE 
         // The first is null, splicing, will remove the second qualified and, after re-stitching 
        the Users = dynamicSqlUserMapper.selectUserLikeByWhere ( null , "China" ); 
        Assert.assertTrue (the Users ! = null );
        Assert.assertTrue (users.size () == 1 ); 


        // the SELECT * from the User 
         // conditions are not in line with, and will not splice sql, "where" keyword was not spliced   
        the Users = dynamicSqlUserMapper.selectUserLikeByWhere ( null , null ); 
        Assert.assertTrue (Users =! null ); 
        Assert.assertTrue (users.size () ==. 5 ); 
        
    }

 

  

Five Dian <trim />

  By the above, <where /> tag is <trim /> tag particular implementation. Sql prefix for attribute within the tag before adding the prefix, represents prefixOverrides attribute values ​​will be used to replace the corresponding prefix in the prefix property <trim />.

     In addition, there suffix suffix property, suffixOverrides rewrite value.

     Below we will replace the label <trim /> <where />.

 

  DynamicSqlUserMapper.java

List<User> selectUserLikeByTrim(@Param("userName") String userName,  @Param("country") String country);

  DynamicSqlUserMapper.xml

   <! - using custom trim element method, replacing WHERE -> 
    < SELECT ID = "selectUserLikeByTrim" The resultMap = "BaseResultMap" > 
        SELECT * from User 
        < trim prefix = "WHERE" prefixOverrides = "the AND | OR" >  <! - prefix characters replace the character corresponding prefixOverrides, prefixOverrides spaces is necessary   -> 
            < IF Test = "null and userName.trim the userName = () length ()> 0!." > 
                USER_NAME like the userName # {} 
            </ IF > 
            < IF Test = "Country!=null and country.trim().length()>0">
                and country like #{country}
            </if>
        </trim>
    </select>

 

  DynamicSqlTests.java

    @Test
     public  void trimTest () {
         // use trim elements, and where to achieve the same effect 
        List <the User> Users = dynamicSqlUserMapper.selectUserLikeByTrim ( "% T", ""); // Country parameter space will be filtered, ? the SELECT * from the User the WHERE user_name like 
        Assert.assertTrue (! the Users = null ); 
        Assert.assertTrue (users.size () > 1 ); 


        // ? the SELECT * from the User Country like the WHERE 
         // The first is null, stitching when will remove the second qualifying and, after re-stitching 
        the Users = dynamicSqlUserMapper.selectUserLikeByTrim ( null , "China" ); 
        Assert.assertTrue (the Users ! = null); 
        Assert.assertTrue (users.size () == 1 ); 


        // the SELECT * from the User 
         // conditions are not in line with, and will not splice sql, "where" keyword was not spliced   
        the Users = dynamicSqlUserMapper.selectUserLikeByTrim ( null , null ); 
        Assert.assertTrue (Users =! null ); 
        Assert.assertTrue (users.size () ==. 5 ); 

    }

 

 

Six Dian <foreach />

   <Foreach /> tag corresponds java for statement, indicating the need to traverse Collection attribute collection object, index when the index attribute indicates traversal, item property indicates the object obtained when the traversal,

       It is used as follows

 

  DynamicSqlUserMapper.java

List<User> selectUserByUserIdsByForeach(@Param("userIds") List<Integer> userIds);

  DynamicSqlUserMapper.xml

    <!-- 4. foreach -->
    <!-- select * from user where user_id in ( ? , ? , ? )  -->
    <select id="selectUserByUserIdsByForeach" resultMap="BaseResultMap">
        select * 
        from user 
        where user_id in 
        <foreach collection="userIds" index="index" item="item" 
                 open="(" separator="," close=")"> <!-- 注意,当collection为map时,index为key, item为value -->
            #{item}
        </foreach>
    </select>
    

 

  DynamicSqlTests.java

    @Test
    public void foreachTest(){
        List<Integer> userIds= Arrays.asList(1,2,3);
        
        // select * from user where user_id in ( ? , ? , ? ) 
        List<User> users=dynamicSqlUserMapper.selectUserByUserIdsByForeach(userIds);
        
        Assert.assertTrue(users!=null);
        Assert.assertTrue(users.size()==3);
        
    }

 

  Click here to view the full source code

 

Learning materials:

  Official Documentation - Dynamic SQL

 

 

Guess you like

Origin www.cnblogs.com/timfruit/p/11386622.html