mybatis 查询单个对象,结果集类型一定要明确

简单介绍:用ssm框架已经有很长时间了,但是似乎从来都没有对于查询单个对象,存在问题的,好像也就是那回事,写完sql就查出来了,也从来都没有认真的想过,为什么会这样,为什么要设置结果集类型

代码:

复制代码
//service层代码
ContractVo contractObj = (ContractVo)dao.findForObject("ContractMapper.getContractObj",contractId);

//Model对象
@Alias("ContractVo")
@Getter
@Setter
public class Contract {
private String contractId;
private String contractNumber;
private String contractType;
private String contractStatus;
private String startTime;
private String endTime;
private String regularAgency;
}

//mapper里的sql相关
<resultMap id="ContractVoResultMap" type="ContractVo">
<result column="contract_id" property="contractId" jdbcType="CHAR"/>
<result column="contract_number" property="contractNumber" jdbcType="VARCHAR"/>
<result column="contract_type" property="contractType" jdbcType="VARCHAR"/>
<result column="contract_status" property="contractStatus" jdbcType="VARCHAR"/>
<result column="start_time" property="startTime" jdbcType="Date"/>
<result column="end_time" property="endTime" jdbcType="Date"/>
<result column="regular_agency" property="regularAgency" jdbcType="VARCHAR"/>
</resultMap> 

<select id="getContractObj" parameterType="String" resultMap="ContractVoResultMap">
select
<include refid="FieldOne"></include>
from
<include refid="tableName"></include>
where contract_id = #{contractId}
</select> 

  <!--字段-->
  <sql id="FieldOne">
contract_id,
contract_number,
contract_type,
contract_status,
start_time,
end_time,
regular_agency
  </sql> 

<!--表名 -->
<sql id="tableName">
t_contract
</sql>
复制代码

 说明:为什么要设置resultMap ,是为了指定sql输出结果所映射的java对象类型,这里select指定resultType表示单条记录所映射成的java对象,也许你会觉得在mapper 文件里配置映射pojo (resultMap-->type="ContractVo"),看着比较生疏,其实和下边的图一个道理。

 

posted @   ジ绯色月下ぎ  阅读(2711)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示