mybatis封装输出结果
resultType#
resultType:执行 sql 得到 ResultSet 转换的类型,使用类型的完全限定名或别名。 注意如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身。resultType 和 resultMap,不能同时使用。
1. 简单类型#
接口方法:
int countStudent();
mapper文件:
<select id="countStudent" resultType="int">
select count(*) from student
</select>
2. 对象类型#
接口方法:
Student selectById(int id);
mapper文件:
<select id="selectById" resultType="com.hzc.domain.Student">
select id,name,email,age from student where id=#{studentId}
</select>
tips: Dao 接口方法返回是集合类型,需要指定集合中的类型,不是集合本身。
3. Map#
sql 的查询结果作为 Map 的 key 和 value。推荐使用Map<Object,Object>。
注意:Map 作为接口返回值,sql 语句的查询结果最多只能有一条记录。大于一条记录是错误。
接口方法:
Map<Object,Object> selectReturnMap(int id);
mapper文件:
<select id="selectReturnMap" resultType="java.util.HashMap">
select name,email from student where id = #{studentId}
</select>
resultMap#
resultMap 可以自定义 sql 的结果和 java 对象属性的映射关系。更灵活的把列值赋值给指定属性。
常用在列名和 java 对象属性名不一样的情况。
使用方式:
1. 先定义 resultMap,指定列名和属性的对应关系。
2. 在<select>中把 resultType 替换为 resultMap。
<resultMap id="student" type="org.example.domain.User">
<id column="uno" property="no"></id>
<result column="uname" property="name" />
<result column="email" property="email" />
</resultMap>
<select id="selectUsers" parameterType="java.lang.String" resultMap="student">
select * from user where uname = #{name}
</select>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理