You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MyBatis与Kotlin实现集合映射时遇“参数类型不匹配”错误

Kotlin + MyBatis 集合映射失败问题

我在Kotlin应用中使用MyBatis时,无法实现简单的集合映射功能。为便于测试,我精简了代码:

data class Role(
    var id: String
)

data class AppUser @AutomapConstructor constructor(
    var id: Int,
    var name: String,
    var email: String,
    var roles: MutableList<Role>
)

interface Mapper {
    fun selectAllUsers(): List<AppUser>
    fun selectAllRoles(): List<Role>
}

同时编写了如下Mapper XML:

<resultMap id="userResultMap" type="de.eekboom.kotlin_mybatis.AppUser">
    <id property="id" column="id" />
    <collection property="roles" javaType="ArrayList" ofType="de.eekboom.kotlin_mybatis.Role">
        <id property="id" column="role_id"/>
    </collection>
</resultMap>

<select id="selectAllUsers" resultMap="userResultMap">
    select u.*, uxr.role_id
    from app_user u
    left join app_user_x_role uxr on u.id = uxr.app_user_id
</select>

<select id="selectAllRoles" resultType="de.eekboom.kotlin_mybatis.Role">
    select * from role
</select>

其中selectAllRoles()可正常运行,但selectAllUsers()执行失败,报错信息如下:

Error instantiating class de.eekboom.kotlin_mybatis.AppUser with invalid
types (int,String,String,List) or values (1,Foo Bar,foo@bar.de,ADMIN).
Cause: java.lang.IllegalArgumentException: argument type mismatch

我查阅了MyBatis的“Result Maps”文档,也尝试了多种变体(比如省略显式javaType或更换Kotlin数据类中的集合类型),但问题依旧。

设计初衷

Kotlin偏好不可变类型,尤其建议将非空属性声明为非空类型。它还提供了可自动生成equals、hashCode和toString实现的数据类,因此我希望:

  • 使用data class
  • 使用不可变属性
  • 使用非空属性,避免后续强制转换为非空类型
  • 使用构造函数注入,确保属性真正不可变,并可添加所有属性初始化完成后执行的初始化代码

内容的提问来源于stack exchange,提问作者eekboom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:32:39