关于在 Mybatis 中使用 record 关键字来定义 JavaBean

经测试,正常情况下使用 record 是没有问题的,但若是使用了 resultMap,将会导致错误:

There is no setter for property named 'xxx' in 'xxx'
argument type mismatch

首先, record 类型没有无参构造函数,所以在反射过程中无法创建对应类型,导致了argument type mismatch错误。

那如果给 record 类型的类加上无参构造函数呢?

会出现以下错误:

There is no setter for property named 'xxx' in 'xxx'

可以看到 Mybatis 可以找到对应的类了,但是仍然会报There is no setter for property named 'xxx' in 'xxx',这是由于 record 类型中所有的变量均为 final 类型,record 也并没有生成 set 方法导致的。

所以总的来说,虽然 record 可以极大的简化 Bean 的编写,并且可以摆脱 Lombok,但是其特性决定了它并不适合用来编写 Mybatis 的 Bean。
除非你的 Bean 的属性只有基本类型(笑


resultMap 部分:

<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher where id = #{tid}
</select>
<resultMap id="studentMapper" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getStudents" resultMap="studentMapper">
select * from mybatis.student;
</select>
posted @   StarChenPy  阅读(743)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体
点击右上角即可分享
微信分享提示