Mybatis如何直接返回SQL结果集 无需创建自定义实体类完成映射
实现方案
Mybatis原生支持无需自定义实体类,直接返回键值对形式的结果集,具体改造步骤如下:
1. 修改Mapper接口
将返回值改为List<Map<String, Object>>,泛型中Map的key为查询结果的列名/别名,value为对应字段值:
package com.employee; import org.apache.ibatis.annotations.Mapper; import java.util.List; import java.util.Map; @Mapper public interface EmployeeMapper { List<Map<String, Object>> retrieveEmployee(); }
2. 修改Mybatis XML映射文件
删除自定义的resultMap,直接将select标签的resultType属性设置为map即可:
<?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" > <mapper namespace="com.employee.EmployeeMapper"> <select id="retrieveEmployee" resultType="map"> select id, employee_name as name, address from employee </select> </mapper>
3. 调用取值示例
完全符合你期望的使用方式,直接通过列名/别名获取对应值:
List<Map<String, Object>> results = employeeMapper.retrieveEmployee(); // 取第一条记录的字段 System.out.println(results.get(0).get("id") + "-" + results.get(0).get("name") + "-" + results.get(0).get("address")); // 输出:1-Tom-123 street // 循环遍历所有记录也可以 for(Map<String, Object> row : results) { Integer id = (Integer) row.get("id"); String name = (String) row.get("name"); String address = (String) row.get("address"); // 自定义业务逻辑 }
补充说明
- 如果查询结果只有一条记录,也可以直接将Mapper返回值设为
Map<String, Object>,不需要套List - 若需要下划线列名自动转驼峰作为Map的key,可以在Mybatis配置文件中开启
mapUnderscoreToCamelCase = true,无需手动写as别名
内容的提问来源于stack exchange,提问作者Hoang Nguyen
相关产品推荐
相关产品推荐

