<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 --> <mapper namespace="com.it.mapper.UserMapper"> <sql id="selectUser"> SELECT * FROM `user` </sql> <!-- 根据多个ID查用户信息 --> <select id="selectUsersByIds" parameterType="com.it.entity.QueryVo" resultType="com.it.entity.User"> <include refid="selectUser"/> <where> <foreach collection="idsList" item="id" separator="," open="id in (" close=")"> #{id} </foreach> </where> </select> </mapper>
UserMapper的映射文件
package com.it.mapper; import java.util.List; import com.it.entity.QueryVo; import com.it.entity.User; public interface UserMapper { public User queryUserById(Integer id); public List<User> findUserByQueryVo(QueryVo vo); //根据多个id查询用户信息 public List<User> selectUsersByIds(QueryVo vo); }
Usermapper接口
package com.it.test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.it.entity.QueryVo; import com.it.entity.User; import com.it.mapper.UserMapper; public class MapperTest { @Test public void testfindUsersByIds() throws Exception{ //加载配置文件 String resource = "SqlMapConfig.xml"; InputStream in = Resources.getResourceAsStream(resource); //创建sessionFactory SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in); //创建sqlSession SqlSession sqlSession = sessionFactory.openSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<Integer> ids = new ArrayList<Integer>(); ids.add(10); ids.add(16); ids.add(22); QueryVo vo = new QueryVo(); vo.setIdsList(ids); List<User> users = userMapper.selectUsersByIds(vo); for (User user : users) { System.out.println(user); } } }
测试方法testfindUsersByIds
时间: 2024-10-06 04:06:34