【问题标题】:Reusing MyBatis ResultMap in multiple mapper.xml在多个 mapper.xml 中重用 MyBatis ResultMap
【发布时间】:2012-11-10 03:57:40
【问题描述】:

我想重新使用来自不同 *Mapper.xml 文件的特定文件,这些文件都以某种方式读取相同的对象。

我有一个名为 Project 的数据库表,我为它创建了以下 resultMap:

<resultMap id="ProjectMap" type="com.model.Project">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="client_prj_no" jdbcType="VARCHAR" property="clientPrjNo" />
    <result column="notes" jdbcType="VARCHAR" property="notes" />
    <result column="start_date" jdbcType="TIMESTAMP" property="startDate" />
    ...
<resultMap>

它在 ProjectMapper.xml 中效果很好,但是,现在我想创建一个 ClientWithProjectsMapper.xml,我想在其中 SELECT * FROM CLIENT, PROJECT where PROJECT.CLIENT_ID = CLIENT.ID 并让 Client 对象返回一个 List对象。换句话说,我想用一条 SQL 获得一个 ClientWithProjects。

在我的映射中,我想重用我在 ProjectMapper.xml 中定义的 ProjectMap(无需复制/粘贴),但我不确定如何实现。

我可以将 ProjectMap 分解到一个单独的文件中,但我没有在 MyBatis 中找到任何工具来#include 其他文件。

关于如何做到这一点的任何想法? (我正在使用 Maven,是否有任何插件可以过滤查找#include 等的文件,并将文件的内容直接包含到正在处理的文件中?)。

谢谢。

-AP_

【问题讨论】:

标签: refactoring mybatis resultset mappers


【解决方案1】:

在 mybatis-config.xml 文件中导入所有映射器 xml 后,您可以使用 resultMap id 和命名空间来引用在任何映射器 xml 中配置的 ResultMaps。

例如: ProjectMapper.xml

<mapper namespace="com.mybatisapp.mappers.ProjectMapper">
    <resultMap id="ProjectMap" type="com.model.Project">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />     
    <resultMap>
</mapper>

在 ClientWithProjectsMapper.xml 中

    <select id="selectProjectsByClient" parameterType="int" 
resultMap="com.mybatisapp.mappers.ProjectMapper.ProjectMap">
    select * from blahblah
    </select>

在这里,您可以使用完全限定名称 "com.mybatisapp.mappers.ProjectMapper.ProjectMap"

在另一个 Mapper xml 文件中引用 resultMap

【讨论】:

  • 有没有办法在映射器之外定义常见的结果映射?例如:我们先包含“resultMaps.xml”,然后“projectMaper.xml”和“clientWithProjectsMapper.xml”将使用“resultMaps.xml”中的常用结果映射。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2018-12-07
相关资源
最近更新 更多