zoukankan      html  css  js  c++  java
  • mybatis的foreach用法

    在做mybatis的mapper.xml文件的时候,我们时常用到这样的情况:动态生成sql语句的查询条件,这个时候我们就可以用mybatis的foreach了

    foreach元素的属性主要有item,index,collection,open,separator,close。

    • item:集合中元素迭代时的别名,该参数为必选。
    • index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
    • open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
    • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
    • close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
    • collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

    • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .
    • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .
    • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.

    针对最后一条,我们来看一下官方说法:

    注意 你可以将一个 List 实例或者数组作为参数对象传给 MyBatis,当你这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。

    所以,不管是多参数还是单参数的list,array类型,都可以封装为map进行传递。如果传递的是一个List,则mybatis会封装为一个list为key,list值为object的map,如果是array,则封装成一个array为key,array的值为object的map,如果自己封装呢,则colloection里放的是自己封装的map里的key值。

    xml代码如下:

        <select id="getUserListByArray" parameterType="int" resultType="User">
            select * from smbms_user
            <where>
                userRole in
                <foreach collection="array" item="roles" open="(" separator="," close=")">
                    #{roles}
                </foreach>
            </where>
        </select>
    
        <select id="getUserListByList" parameterType="Integer" resultType="User">
            select * from smbms_user
            <where>
                userRole in 
                <foreach collection="list" item="rolesList" open="(" separator="," close=")">
                    #{rolesList}
                </foreach>
            </where>
        </select>
    
        <select id="getUserListByMap" resultType="User" parameterType="map">
            select * from smbms_user
            <where>
                userCode like CONCAT ('%',#{userCode},'%')
                and userRole in
                <foreach collection="userRole" item="userRole" open="(" separator="," close=")">
                    #{userRole}
                </foreach>
            </where>
        </select>

    Dao层接口代码如下:

     /**
         * getUserListByArray
         * foreach int数组
         * @param roles
         * @return
         * @throws Exception
         */
        public List<User> getUserListByArray(int[] roles) throws Exception;
    
        /**
         * getUserListByList
         * 通过集合查询数据
         * 形参为list
         * @param rolesList
         * @return
         * @throws Exception
         */
        public List<User> getUserListByList(List<Integer> rolesList) throws Exception;
    
        /**
         * getUserListByMap
         * 通过map来查询数据
         * 形参为map
         * @param map
         * @return
         * @throws Exception
         */
        public List<User> getUserListByMap(Map map) throws Exception;
    
        /**
         * getUser_choose
         *
         * @param user
         * @return
         * @throws Exception
         */
        public List<User> getUser_choose(User user) throws Exception;

    测试代码如下:

    @Test
        public void testUserListByArray_foreach(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            int[] ints={1,2};
            try {
                List<User> userListByArray = sqlSession.getMapper(UserMapper.class).getUserListByArray(ints);
                for (User _uer:userListByArray){
                    System.out.println(_uer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                sqlSession.close();
            }
        }
    @Test
        public void testUserListByList_foreach(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            List<Integer> integerList=new ArrayList<Integer>();
            integerList.add(1);
            integerList.add(2);
            try {
                List<User> userListByList = sqlSession.getMapper(UserMapper.class).getUserListByList(integerList);
                for (User _user:userListByList
                     ) {
                    System.out.println(_user);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                sqlSession.close();
            }
        }
    
    @Test
        public void testUserListByMap(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            Integer[] roles={1,2};
            Map map=new HashMap();
            map.put("userRole",roles);
            map.put("userCode","a");
    
            try {
                List<User> userListByMap = sqlSession.getMapper(UserMapper.class).getUserListByMap(map);
                for (User _user:userListByMap){
                    System.out.println(userListByMap);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                sqlSession.close();
            }
        }
    
        @Test
        public void testUser_choose(){
            SqlSession sqlSession = MybatisUtil.getSqlSession();
            User user=new User();
            user.setUserCode("a");
            //user.setUserName("李");
            user.setUserPassword("3");
            Date date=new Date();
            user.setCreationDate(date);
            try {
                List<User> user_choose = sqlSession.getMapper(UserMapper.class).getUser_choose(user);
                for (User _user:user_choose){
                    System.out.println(_user);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                sqlSession.close();
            }
    
        }
  • 相关阅读:
    LeetCode Array Easy 414. Third Maximum Number
    LeetCode Linked List Medium 2. Add Two Numbers
    LeetCode Array Easy 283. Move Zeroes
    LeetCode Array Easy 268. Missing Number
    LeetCode Array Easy 219. Contains Duplicate II
    LeetCode Array Easy 217. Contains Duplicate
    LeetCode Array Easy 189. Rotate Array
    LeetCode Array Easy169. Majority Element
    LeetCode Array Medium 11. Container With Most Water
    LeetCode Array Easy 167. Two Sum II
  • 原文地址:https://www.cnblogs.com/CjtBlog/p/13960854.html
Copyright © 2011-2022 走看看