一、批量操作——查询
在实际工作,我们需要根据情况进行批量查询,批量查询,可以全部查询出来,也可以根据其他查询查询出来。
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();
}
}
分类:
MyBatis
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战