您的位置:首页 > 其它

MyBatis结果集处理,中resultType和resultMap的区别

2018-02-05 17:08 281 查看
http://blog.csdn.net/leo3070/article/details/77899574

使用resultType
<select id="selectUsers" parameterType="int" resultType="com.someapp.model.User">  select id, username, hashedPassword  from some_table  where id = #{id}</select>
这些情况下,MyBatis 会在幕后自动创建一个 ResultMap(其实MyBatis的每一个查询映射的返回类型都是ResultMap),基于属性名来映射列到 JavaBean 的属性上


如果列名没有精确匹配,你可以在列名上使用 select 字句的别名(一个 基本的 SQL 特性)来匹配标签。比如:

<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>

resultType可以直接返回给出的返回值类型,比如String、int、Map,等等,其中返回List也是将返回类型定义为Map,然后mybatis会自动将这些map放在一个List中,resultType还可以是一个对象-属性名自动映射

使用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>
外部resultMap的type属性表示该resultMap的结果是一个什么样的类型, esultMap节点的子节点id是用于标识该对象的id的,而result子节点则是用于标识一些简单属性的,其中的Column属性表示从数据库中查询的属性,Property则表示查询出来的属性对应的值赋给实体对象的哪个属性。

注意:用resultType的时候,要保证结果集的列名与java对象的属性相同,而resultMap则不用,而且resultMap可以用typeHander转换

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: