MyBatis——ORM
- 验证映射配置
- ResultType本质是ResultMap
- 具体的转换逻辑
概括的说,MyBatis中,对于映射关系的声明是由开发者在xml文件手动完成的。比如对查询方法而言,你需要显式声明ResultType或ResultMap,这里其实就是在定义数据库字段和Java属性之间的映射关系。
验证映射配置
<select id="queryWithoutType">
select * from user where id = #{id}
</select>
<select id="queryWithReturnType" resultType="org.wyy.dto.User">
select * from user where id = #{id}
</select>
<select id="queryWithReturnMap" resultType="org.wyy.dto.User">
select * from user where id = #{id}
</select>
这里我们定义三个相同逻辑的方法,方法1不声明映射关系。分别运行三个方法,方法2和方法3正常执行,方法1抛出异常如下,说明ORM的转换关系需要在xml中每个方法里显示声明(即手动配置)。
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
'org.wyy.mapper.UserMapper.queryWithoutType'.
It's likely that neither a Result Type nor a Result Map was specified.
ResultType本质是ResultMap
从上图可以看出,当ResultMap为空但ResultType不为空时,会默认创建一个后缀为-Inline
的ResultMap,所以MyBatis中ORM最终的参照是ResultMap对象
具体的转换逻辑
该部分其实是ibatis中实现的(未完待)