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

发布时间 2023-05-20 17:08:38作者: Starsdust

经测试,正常情况下使用 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 方法导致的。


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>