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

如何在MyBatis多Mapper.xml的association关联中复用ResultMap

MyBatis ResultMap跨Mapper复用方案

实现步骤

  1. 为存放公共ResultMap的Mapper配置唯一namespace
    首先给pationt-mapper.xml的根<mapper>标签添加namespace属性,一般对应Mapper接口的全限定类名,示例如下:
<mapper namespace="com.yourproject.mapper.PatientMapper">
    <resultMap type="Pationt" id="PationtResult">
        <id property="id" column="id"/>
        <result property="firstname" column="firstname"/>
        <result property="lastname" column="lastname"/>
        <result property="createdAt" column="created_at"/>
    </resultMap>
    <!-- 其他该Mapper下的SQL配置 -->
</mapper>
  1. 其他Mapper中通过「命名空间.结果集ID」格式引用
    你可以直接删除report-mapper.xml中重复的PationtResult配置,在association标签的resultMap属性中填写全限定的ResultMap标识即可:
<resultMap type="Report" id="ReportResult">
    <id property="id" column="id"/>
    <result property="reportText" column="report_text"/>
    <result property="lastname" column="lastname"/>
    <result property="createdAt" column="created_at" />
    <association property="pationt" resultMap="com.yourproject.mapper.PatientMapper.PationtResult" />
</resultMap>

注意事项

  • 保证被引用的Mapper文件已经被MyBatis正常加载,比如在全局配置中配置了Mapper扫描路径、或者通过Spring的Mapper扫描器纳入上下文,否则会抛出找不到ResultMap的异常。
  • 如果多个Mapper属于同一个命名空间,也可以直接填写ResultMap的id引用,不过建议优先使用全限定名避免id重复导致的冲突。

内容的提问来源于stack exchange,提问作者Abdalrazag Al-Shrufat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:24:05