欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis foerach多条件查询

程序员文章站 2022-03-11 21:42:49
...

比如,我们要查找很多id的user1,31…
解释下foreach中各个参数意思:

  • foreach元素的属性主要有 item,index,collection,open,separator,close。
  1. item表示集合中每一个元素进行迭代时的别名,

  2. index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,

  3. open表示该语句以什么开始,

  4. separator表示在每次进行迭代之间以什么符号作为分隔 符,

  5. close表示以什么结束。
    UserMapper.xml

<select id="findUserByMoreId"  parameterType="list" resultType="com.company.User">
        select id,name,password from user where  id in
        <foreach collection="list" item="item" separator="," open="(" close=")" index="index">
            #{item}
        </foreach>
    </select>

照着写就行,需要修改自己参数.
测试类:

 @Test
    public void findUserByMoreId () throws IOException {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        //建立会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<Integer> list= Arrays.asList(1,31);
        List<User> userList=mapper.findUserByMoreId(list);
        System.out.println(userList);
        sqlSession.close();

    }

接口mapper:

 List<User> findUserByMoreId (List<Integer> list);
 

结果显示:

2019-05-30 08:59:48,726 [main] DEBUG [com.mapper.UserMapper] - Cache Hit Ratio [com.mapper.UserMapper]: 0.0
2019-05-30 08:59:49,549 [main] DEBUG [com.mapper.UserMapper.findUserByMoreId] - ==>  Preparing: select id,name,password from user where id in ( ? , ? ) 
2019-05-30 08:59:49,675 [main] DEBUG [com.mapper.UserMapper.findUserByMoreId] - ==> Parameters: 1(Integer), 31(Integer)
2019-05-30 08:59:49,744 [main] DEBUG [com.mapper.UserMapper.findUserByMoreId] - <==      Total: 2
[User{id=1, name='帅帅', password='帅帅', aClass=null, listTea=null}
, User{id=31, name='jok1', password='jok1', aClass=null, listTea=null}
]

希望对大家有帮助!!!