MyBatis_动态sql语句_hehe.employment.over.31.2

31.3 MyBatis中的动态sql语句

31.3.1 if 标签

  • <if>标签的test属性中写的是对象的属性名,如果是包装类的对象要使用OGNL表达式的写法。
    <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 标签

    <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 标签

  • SQL 语句: select 字段from user where id in (?)
    • <foreach>标签用于遍历集合,它的属性:
      • collection:代表要遍历的集合元素,注意编写时不要写#{}
      • open:代表语句的开始部分
      • close:代表结束部分
      • item:代表遍历集合的每个元素,生成的变量名
      • sperator:代表分隔符
    <!-- 根据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);
        }

    }

猜你喜欢

转载自blog.csdn.net/qq_44686266/article/details/114041068
今日推荐