如何在MyBatis多Mapper.xml的association关联中复用ResultMap
MyBatis ResultMap跨Mapper复用方案
实现步骤
- 为存放公共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>
- 其他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
相关产品推荐
相关产品推荐

