问题记录-A query was run and no Result Maps were found for the Mapped Statement..

A query was run and no Result Maps were found for the Mapped Statement…

1.报错信息

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'xxx'.  It's likely that neither a Result Type nor a Result Map was specified.

2.问题分析
由报错信息可知: 很可能既没有指定结果类型, 也没有指定结果映射。
检查mapper.xml文件后, 发现遗漏了里面一个属性resultType=" " 或者 resultMap=" "

<!--报错的配置-->
<select id="selectDiscussPosts">
    select <include refid="selectFields"></include>
    from discuss_post
    where status != 2
    <if test="userId!=0">
        and user_id = #{userId}
    </if>
    order by type desc, create_time desc
    limit #{offset}, #{limit}
</select>

MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap.
resultType是直接表示返回类型的,适用于单表查询并且结果字段与属性一致.
resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在,如果resultType不满足要求,就用到了resultMap完成映射.

注意:
只有查询需要写resultType
如果是"更新"操作可以自动返回影响的函数

3.解决方法
在< select >标签上加上属性resultType=" "即可

<select id="selectDiscussPosts" resultType="DiscussPost">
...
</select>

在resultType=“DiscussPost”中,DiscussPost就是自定义的POJO,此时可以使用全限定类名 (全限定类名:就是类名全称,带包路径的用点隔开,例如: java.lang.String) 来指定这些POJO的引用.
但这里resultType没写全是因为在配置文件使用mybatis.type-aliases-package来指定POJO扫描包来让mybatis自动扫描到自定义的POJO。

mybatis.type-aliases-package=com.example.demo.entity

4.其他 —resultMap补充
有这样一个问题: 如果结果集中的数据与POJO不能做到一一对应,会出现什么情况呢?例如:
起别名

<select id="findAll" resultType="User">
    select id as user_id, name as user_name, age user_age, sex user_sex
    from demo_user
</select>

测试方法

/**
* 测试需求: 检查结果的字段和属性不对应的状态
*/
@Test
public void testResult(){
    List<User> list = userMapper.findAll();
    System.out.println(list);
}

测试结果:
在这里插入图片描述
可以看到结果全是null, 这是因为resultType适用于单表查询并且结果字段与属性一致,如果不一致就会出现上述结果,那该怎么办?这里就用到了resultMap

<select id="findAll" resultMap="resultUser">
    select id as user_id, name as user_name, age user_age, sex user_sex
    from demo_user
</select>
<resultMap id="resultUser" type="User">
    <!--id是主键,必须添加-->
    <id column="user_id" property="id"/>
    <!--其他属性-->
    <result column="user_name" property="name"/>
    <result column="user_age" property="age"/>
    <result column="user_sex" property="sex"/>
</resultMap>

测试结果
在这里插入图片描述
🆗了

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值