一、批量操作——查询
在实际工作,我们需要根据情况进行批量查询,批量查询,可以全部查询出来,也可以根据其他查询查询出来。
1、查询全部的数据
(1)在接口中声明方法
//查询所有对象,返回 list 集合
public List<Employee> getAllEmps();
(2)在对应的 xml 中配置
<!-- public List<Employee> getAllEmps(); resultType:如果返回的是一个集合,要写集合中元素的类型 指定集合中存放的类型,有多个数据,会自动转换为要返回的类型 -->
<select id="getAllEmps" resultType="com.njf.mybatis.bean.Employee"> select id, last_name lastName, email, gender from tbl_employee </select>
2、根据指定条件批量查询
(1)在接口中声明方法
//根据指定的id来查询
public List<Employee> getEmpsByIds(@Param("ids")List<Integer> ids);
(2)在对应的 xml 中配置
<!-- //根据指定的id来查询 public List<Employee> getEmpsByIds(@Param("ids")List<Integer> ids); -->
<!-- 方式一:select * from tbl_employee where id in (1,2,3); -->
<select id="getEmpsByIds" resultType="Employee" databaseId="oracle"> select * from tbl_employee <foreach collection="ids" item="item" open="where id in(" close=")" separator=","> #{item} </foreach>
</select>
<!-- 方式二:select * from tbl_employee where id = 1 or id = 2 or id = 3 -->
<select id="getEmpsByIds" resultType="Employee"> select * from tbl_employee <foreach collection="ids" item="item" open="where" separator="or"> id = #{item} </foreach>
</select>
3、根据多条件查询
(1)在接口中声明方法
//根据多条件查询
public List<Employee> getEmpsByCondition(Employee employee);
(2)在对应的 xml 中配置
<!-- public List<Employee> getEmpsByCondition(Employee employee); --> <select id="getEmpsByCondition" resultType="Employee"> select * from tbl_employee <where> <if test="id!=null"> id=#{id} </if> <if test="lastName!=null and lastName!=''"> and last_name like #{lastName} </if> <if test="email!=null and email.trim()!="""> and email = #{email} </if> <if test="gender!=null and gender==0 or gender==1"> and gender = #{gender} </if> </where> </select>
测试:
@Test public void testBatchSelect() throws IOException { //1、获取 sqlSessionFactory
SqlSessionFactory sqlSessionFactory = getsqlSessionFactory(); //2、获取 sqlSession 实例,能直接执行已经映射的 SQL 语句
SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapperBatch mapper = sqlSession.getMapper(EmployeeMapperBatch.class); List<Employee> emps = new ArrayList<>(); //查询所有的员工信息
emps = mapper.getAllEmps(); //根据指定的id来查询
emps = mapper.getEmpsByIds(Arrays.asList(1, 3)); //多条件查询
emps = mapper.getEmpsByCondition(new Employee(null, "%o%", null, null)); emps.forEach(System.out::println); } finally { sqlSession.close(); } }