Mybatis 中 resultMap 和 resultType 的使用
其实在一般进行多表查询 或者 单表 查询时 result Map和result Type都达到要求
一丶在使用resultType时
<select id="selectUsers" parameterType="int" resultType="com.someapp.model.User">
select id, username, hashedPassword
from some_table
where id = #{id}
</select>
在这种情况下,Mybatis会在 幕后 自动 创建一个 result Map,基于属性名来影射列 到 JavaBean 的属性上。如果列名没有 精确 匹配到 ,我就可以 在列名上使用一select 字句的 别名 来 匹配 标签,例如:
<select id="selectUsers" parameterType="int" resultType="User">
select
user_id as "id",
user_name as "userName",
hashed_password as "hashedPassword"
from some_table
where id = #{id}
</select>
二丶使用resultMap
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<select id="selectUsers" parameterType="int" resultMap="userResultMap">
select user_id, user_name, hashed_password
from some_table
where id = #{id}
</select>
相同点:两者 都映射到了 User中
不同:
1.resultMap:指的是定义好了的id的,是定义好的resyltType的引用
注意:用resultType的时候,要保证结果集的列名与java对象的属性相同,而resultMap则不用,而且resultMap可以用typeHander转换
2.type:java 对象对应的类,id:在本文件要唯一column :数据库的列名或别名,property:对应java对象的属性,jdbcType:java.sql.Types
查询语句中,resultMap属性指向上面那个属性的标签的id
parameterType:参数类型,只能传一个参数,如果有多个参数要封装,如封装成一个类,要写包名加类名,基本数据类型则可以省略
3.一对1、一对多时,若有表的字段相同必须写别名,不然查询结果无法正常映射,出现某属性为空或者返回的结果与想象中的不同,而这往往是没有报错的。