当前位置: 首页 > 工具软件 > 重名修改 > 使用案例 >

mybatis的resultMap中字段重名处理

易扬
2023-12-01

问题

在写mybatis的关联查询时,resultMap中如果两个对象有相同的属性。查询出来的结果内层的对象的属性会被外层对象属性覆盖,导致内层list数据出错。

resultMap结构如下:

<resultMap id="DetailResultMap" type="com.tchirk.itsm.ca.domain.System">
        <result column="object_version_number" jdbcType="BIGINT" property="objectVersionNumber"/>
        <result column="created_by" jdbcType="BIGINT" property="createdBy"/>
        <result column="creation_date" jdbcType="TIMESTAMP" property="creationDate"/>
        <collection property="moduleList" ofType="com.tchirk.itsm.ca.domain.Module">
            <result column="object_version_number" jdbcType="BIGINT" property="objectVersionNumber"/>
            <result column="created_by" jdbcType="BIGINT" property="createdBy"/>
            <result column="creation_date" jdbcType="TIMESTAMP" property="creationDate"/>
        </collection>
    </resultMap>

查询关联对象的SELECT语句如下

<select id="selectSystem" resultMap="DetailResultMap" resultType="com.tchirk.itsm.ca.domain.System">
    SELECT
        s1.object_version_number,
        s1.last_updated_by,
        s1.last_update_date,
        m1.object_version_number,
        m1.last_updated_by,
        m1.last_update_date
        FROM itsm_system s1
        left join itsm_module m1
           on m1.system_id=s1.system_id
</select>

解决

将关联对象的相同属性名重命名,然后在resultMap中将column属性修改为查询语句中重命名的名字。

<select id="selectSystem" resultMap="DetailResultMap" resultType="com.tchirk.itsm.ca.domain.System">
    SELECT
        s1.object_version_number,
        s1.last_updated_by,
        s1.last_update_date,
        m1.object_version_number m1_object_version_number,
        m1.last_updated_by m1_last_updated_by,
        m1.last_update_date m1_last_update_date
        FROM itsm_system s1
        left join itsm_module m1
           on m1.system_id=s1.system_id
</select>
    <resultMap id="DetailResultMap" type="com.tchirk.itsm.ca.domain.System">
       <result column="object_version_number" jdbcType="BIGINT" property="objectVersionNumber"/>
       <result column="created_by" jdbcType="BIGINT" property="createdBy"/>
       <result column="creation_date" jdbcType="TIMESTAMP" property="creationDate"/>
       <collection property="moduleList" ofType="com.tchirk.itsm.ca.domain.Module">
           <result column="m1_object_version_number" jdbcType="BIGINT" property="objectVersionNumber"/>
           <result column="m1_created_by" jdbcType="BIGINT" property="createdBy"/>
           <result column="m1_creation_date" jdbcType="TIMESTAMP" property="creationDate"/>
       </collection>
   </resultMap>
 类似资料: