在Mybatis中,ResultType和ResultMap的区别是什么,其分别如何使用?
时间: 2024-03-17 15:47:43 浏览: 71
在Mybatis中,ResultType和ResultMap都是用于指定查询结果的映射方式,但它们的使用方式和作用有所不同。
- ResultType
ResultType是指定查询结果的类型,通常情况下可以指定为JavaBean的全限定名,或者是Java基本数据类型的别名。Mybatis会根据查询结果的列名和JavaBean的属性名进行自动映射,将查询结果封装为JavaBean对象。
使用方式如下:
<select id="selectUser" resultType="com.example.User">
select id, name, age from user where id=#{id}
</select>
在上述例子中,查询结果会被自动映射为com.example.User对象。
- ResultMap
ResultMap是指定查询结果的映射规则,可以自定义映射规则,包括列名和JavaBean属性名的对应关系,以及一些高级映射规则,如关联查询、嵌套查询等。
使用方式如下:
<resultMap id="userMap" type="com.example.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectUser" resultMap="userMap">
select id, name, age from user where id=#{id}
</select>
在上述例子中,自定义了一个id为userMap的ResultMap,指定了列名和JavaBean属性名的对应关系,然后在select语句中使用了这个ResultMap。查询结果会按照ResultMap的规则进行映射,将查询结果封装为com.example.User对象。
总之,ResultType和ResultMap都是用于指定查询结果的映射方式,ResultType适用于简单的映射,ResultMap适用于复杂的映射。开发人员可以根据具体情况选择合适的方式来进行结果映射。
相关推荐


















