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>
测试结果
🆗了