mybatis映射时候的注意点

另外,请注意,结果映射中使用了column="sh.id",这意味着MyBatis会查找结果集中列名为sh.id的列。但是,在SQL中,我们使用sh.id作为列名,这会导致结果集中的列名也是sh.id(包括别名中的点)。

这可能会引起问题,因为点通常用于嵌套结果映射。实际上,在SQL中,使用sh.id作为列名,结果集中的列名会是sh.id(字符串),而不是id。这可能导致MyBatis无法正确映射。

1. 检查SQL别名和结果映射的对应关系

你的SQL是:

sql

复制代码
SELECT sh.id,sh.history_id,sh.announcement_id,u.id,u.avatar_url,u.nickname

但结果映射是:

xml

复制代码
<resultMap id="SeeHistoryWithUserVOResult" type="com.hgwy.notification.business.vo.SeeHistoryWithUserVO">
    <result property="id" column="sh.id"/>          <!-- SQL中是 sh.id -->
    <result property="userId" column="u.id"/>       <!-- SQL中是 u.id -->
    <result property="announcementId" column="sh.announcement_id"/>
    <result property="historyId" column="sh.history_id"/>
    <result property="avatarUrl" column="u.avatar_url"/>
    <result property="nickname" column="u.nickname"/>
</resultMap>

问题 :SQL中的列名是sh.id,但结果映射期望的列名是sh.id。实际上,SQL返回的列名中会包含.,这可能导致MyBatis无法正确映射。

2. 修改SQL使用别名(推荐)

将SQL修改为使用明确的无点号别名:

xml

复制代码
<select id="selectSeeHistoryUserList" parameterType="Long" resultMap="SeeHistoryWithUserVOResult">
    SELECT 
        sh.id as sh_id,
        sh.history_id as history_id,
        sh.announcement_id as announcement_id,
        u.id as user_id,
        u.avatar_url as avatar_url,
        u.nickname as nickname
    FROM see_history sh  
    LEFT JOIN `user` u ON sh.user_id = u.id 
    WHERE sh.announcement_id = #{announcementId}
</select>

相应地修改结果映射:

xml

复制代码
<resultMap id="SeeHistoryWithUserVOResult" type="com.hgwy.notification.business.vo.SeeHistoryWithUserVO">
    <result property="id" column="sh_id"/>
    <result property="userId" column="user_id"/>
    <result property="announcementId" column="announcement_id"/>
    <result property="historyId" column="history_id"/>
    <result property="avatarUrl" column="avatar_url"/>
    <result property="nickname" column="nickname"/>
</resultMap>
相关推荐
墨夶2 小时前
Java冷热钱包:不是所有钱包都叫“双保险“!用户资产安全的终极守护者
java·安全·区块链
玄〤2 小时前
MyBatis-Plus 核心功能详解:条件构造器、Service 封装与批量优化实践(黑马springcloud微服务课程)(day2)
spring cloud·微服务·mybatis
我要神龙摆尾3 小时前
约定俗成的力量--java中泛型的意义和用法
java·开发语言
毅炼3 小时前
hot100打卡——day14
java·数据结构·算法·leetcode·ai·深度优先·哈希算法
C雨后彩虹3 小时前
优雅子数组
java·数据结构·算法·华为·面试
一嘴一个橘子3 小时前
springmvc 全局异常处理 and 拦截器
java
wangmengxxw3 小时前
SpringAI-mysql
java·数据库·人工智能·mysql·springai
Coder_Boy_3 小时前
基于SpringAI的在线考试系统-数据库设计核心业务方案
java·数据库·spring boot·ddd·tdd
一嘴一个橘子3 小时前
springmvc 参数校验
java