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

如何在MyBatis的resultMap中捕获查询语句中的新增列(current_date)

问题描述

在操作plugin表时,能够正常捕获id列的记录,但对于不属于该表的计算列(比如current_date),不知道如何捕获其返回值。

现有代码如下:

mapper.xml 代码

<resultMap type="my.class.plugins.Plugin" id="pluginMap">
    <constructor>
        <idArg column="id" javaType = "java.util.UUID"/>
    </constructor>
</resultMap>

<select id="getPluginById" resultMap="pluginMap">
 SELECT id, current_date
 FROM public.plugin
</select>

Java 实体类代码

@Value.Immutable
@JsonSerialize
@JsonDeserialize(as = ImmutablePlugin.class)
@Value.Style(allParameters = true)
public abstract class Plugin {

    public Plugin() {

    }

    /**
     * returns id from table plugin
     * @return
     */
    public abstract UUID getId();
}
解决方案

要获取这类非表的计算列值,只需完成以下两处修改:

1. 更新Java抽象类,新增对应属性的抽象方法

由于使用了Immutable注解(@Value.Immutable),需要在抽象类Plugin中新增currentDate的抽象方法,框架会自动生成该属性的实现逻辑:

@Value.Immutable
@JsonSerialize
@JsonDeserialize(as = ImmutablePlugin.class)
@Value.Style(allParameters = true)
public abstract class Plugin {

    public Plugin() {

    }

    public abstract UUID getId();
    // 新增currentDate的抽象方法,类型匹配SQL返回的日期类型
    public abstract LocalDate getCurrentDate();
}

注:SQL的current_date对应Java 8+的LocalDate类型,若使用旧版本Java,可替换为java.sql.Date。

2. 修改MyBatis的ResultMap,完成列映射

在resultMap的构造函数注入节点中,添加arg元素将SQL的current_date列映射到新增的currentDate属性。建议给SQL中的计算列设置别名,确保映射关系清晰:

<resultMap type="my.class.plugins.Plugin" id="pluginMap">
    <constructor>
        <idArg column="id" javaType="java.util.UUID"/>
        <!-- 新增current_date的映射,name对应Java属性名,column对应SQL列名/别名 -->
        <arg column="current_date" javaType="java.time.LocalDate" name="currentDate"/>
    </constructor>
</resultMap>

<select id="getPluginById" resultMap="pluginMap">
 SELECT id, current_date as current_date
 FROM public.plugin
</select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:20:38