使用foreach解析输入参数数组

来源:互联网 发布:2016淘宝好评返现违规 编辑:程序博客网 时间:2024/06/06 20:37

背景:

SELECT * FROM `user` WHERE sex = '0' and (id = 1 or id = 2 or id =3)//或者SELECT * FROM `user` WHERE sex = '0' and id IN(1,2,3)


第一步在pojo类的包装类中加入

private List<Integer> ids;

并生成get/set方法

第二部修改mapper.xml文件

 <!-- sql片段         建议:对单表进行sql片段的抽取,方便重用            抽取时不包含where     -->     <sql id="findUserSql">        <if test="userCustomer!=null">                <if test="userCustomer.sex!=null and userCustomer.sex!=''">                    and user.sex=#{userCustomer.sex}                </if>                <if test="userCustomer.address!=null and userCustomer.address!=''">                    and user.address like '$%{userCustomer.address}%'                </if>                <if test="ids!=null">                    <!-- collection:指定输入对象的集合属性                        item:每一个遍历生成的对象                        open:开始遍历串拼接串                        close:结束拼接时遍历的串                        separator:遍历的两个对象中间需要拼接的串                     -->                     <!-- 使用实现这个串的拼接and(id = 1 or id = 2 or id =3) -->                    <foreach collection="ids" item="i_id" open="and(" close=")" separator="or">                        id = #{i_id}                    </foreach>                </if>        </if>     </sql>

第二种情况

 <!-- 使用实现这个串的拼接 and id IN(1,2,3) --><foreach collection="ids" item="i_id" open="and id IN(" close=")" separator=",">    #{i_id}</foreach>

接口不需要改

测试:

@Test    public void findUserCount() throws Exception{        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);        //构建一个包装类        UserQueryVo userQueryVo = new UserQueryVo();        //构建一个增强类        UserCustomer userCustomer = new UserCustomer();        userCustomer.setAddress("明月");        //包装类包装这增强类作为查询条件        userQueryVo.setUserCustomer(userCustomer);        ArrayList<Integer> ids = new ArrayList<Integer>();        ids.add(1);        ids.add(2);        ids.add(3);        userQueryVo.setIds(ids);        List<UserCustomer> userList = usermapper.fingUserList(userQueryVo);        sqlSession.close();        for (UserCustomer user : userList) {            System.out.println(user);        }    }
原创粉丝点击