MyBatis_dynamic sql statement_hehe.employment.over.31.2

31.3 Dynamic sql statement in MyBatis

31.3.1 if tag

  • <if>The test attribute of the label writes the attribute name of the object. If it is an object of the packaging class, use the OGNL expression.
    <select id="findUserByCondition" resultType="com.xww.domain.User" parameterType="com.xww.domain.User">
        select * from user where 1=1
        <if test="username != null">
           and username = #{username}
        </if>
    </select>

31.3.2 where tag

    <select id="findUserByCondition" resultType="com.xww.domain.User" parameterType="com.xww.domain.User">
        select * from user where
        <where>
            <if test="username != null">
                and username = #{username}
            </if>
            <if test="sex != null">
                and sex = #{sex}
            </if>
        </where>
    </select>

31.3.3 forEach tag

  • SQL statement: select 字段from user where id in (?)
    • <foreach>The tag is used to traverse the collection, its attributes:
      • collection : representativeCollection element to be traversed, Pay attention to when writingDon't write #{}
      • open : represents the statementBeginning part
      • close : representativeEnd part
      • item : represents each element of the traversal collection, generatedvariable name
      • sperator : representativeDelimiter
    <!-- 根据queryvo中的Id集合实现查询用户列表 -->
    <select id="findUserInIds" resultType="com.xww.domain.User" parameterType="com.xww.domain.QueryVo">
        select * from user
        <where>
            <if test="ids != null and ids.size()>0">
                <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>
    /**
     * 测试foreach标签的使用
     */
    @Test
    public void testFindInIds(){
    
    
        QueryVo vo = new QueryVo();
        List<Integer> list = new ArrayList<Integer>();
        list.add(41);
        list.add(42);
        list.add(46);
        vo.setIds(list);

        //5.执行查询所有方法
        List<User> users = userDao.findUserInIds(vo);
        for(User user : users){
    
    
            System.out.println(user);
        }

    }

Guess you like

Origin blog.csdn.net/qq_44686266/article/details/114041068