mybatis resultMap继承
时间: 2023-08-26 22:10:38 浏览: 47
MyBatis 中的 resultMap 和 resultType 是两种不同的查询结果映射方式。
resultType 是基于类型的映射,适用于返回结果为单一类型的情况,例如返回一个整型或字符串。
resultMap 是基于映射关系的映射,适用于返回结果为复杂类型的情况,例如返回一个对象或一组对象。
相关问题
Mybatis resultMap详解
在 Mybatis 中,ResultMap 是一种将查询结果集映射到 Java 对象中的技术,它可以自定义对查询结果集的映射方式,使得查询结果集中的列与 Java 对象的属性进行映射,从而方便进行数据操作。下面详细介绍一下 Mybatis 中的 ResultMap。
### ResultMap 的定义
ResultMap 的定义可以在 Mapper.xml 文件中使用 <resultMap> 标签进行定义,示例代码如下:
```xml
<resultMap id="userMap" type="com.example.User">
<id property="id" column="user_id" />
<result property="username" column="user_name"/>
<result property="age" column="user_age"/>
</resultMap>
```
其中:
- `id`:ResultMap 的唯一标识符;
- `type`:映射结果集的 Java 类型;
- `id` 和 `result`:用来映射结果集中的列和 Java 对象的属性,其中 `id` 用来映射主键,`property` 表示 Java 对象的属性名,`column` 表示查询结果集中的列名。
### ResultMap 的使用
在 Mapper.xml 文件中的 SQL 语句中使用 ResultMap,示例代码如下:
```xml
<select id="selectUser" resultMap="userMap">
select user_id, user_name, user_age from user where user_id = #{id}
</select>
```
其中,`resultMap` 属性指定了使用的 ResultMap 的 id。
### ResultMap 的继承
Mybatis 还支持 ResultMap 的继承,可以通过 extends 属性来实现。示例代码如下:
```xml
<resultMap id="userMap" type="com.example.User">
<id property="id" column="user_id" />
<result property="username" column="user_name"/>
<result property="age" column="user_age"/>
</resultMap>
<resultMap id="userMapWithAddress" type="com.example.User" extends="userMap">
<result property="address" column="user_address"/>
</resultMap>
```
在上面的示例中,`userMapWithAddress` 继承了 `userMap`,因此可以使用 `userMap` 中定义的映射关系,同时还可以添加自己的映射关系。
### ResultMap 的自动映射
Mybatis 还支持自动映射,它会根据查询结果集中的列名自动匹配 Java 对象中的属性名,从而省略 ResultMap 的定义。可以使用 `autoMapping="true"` 来启用自动映射。示例代码如下:
```xml
<select id="selectUser" resultType="com.example.User" autoMapping="true">
select user_id, user_name, user_age from user where user_id = #{id}
</select>
```
在上述代码中,`resultType` 属性指定了映射结果集的 Java 类型,而 `autoMapping` 属性启用了自动映射。
### 总结
- Mybatis 的 ResultMap 是将查询结果集映射到 Java 对象中的技术;
- ResultMap 可以在 Mapper.xml 文件中定义,并在 SQL 语句中使用;
- ResultMap 可以继承,可以自动映射。
resultMap继承
在Java中,`resultMap`并不能继承,因为它是一个MyBatis框架中用于映射查询结果的配置项。`resultMap`用于定义查询结果的映射规则,将数据库中的列与对象属性进行映射。它是在MyBatis的映射文件中使用的一个配置项。
但是,在MyBatis中,可以使用继承来复用和扩展已有的`resultMap`。可以定义一个基本的`resultMap`,然后在子类的`resultMap`中引用并扩展基本的`resultMap`。这样可以减少代码的重复,并且方便进行修改和维护。
例如,假设有一个基本的`resultMap`定义如下:
```xml
<resultMap id="BaseResultMap" type="com.example.BaseEntity">
<id column="id" property="id" />
<result column="name" property="name" />
<!-- 其他属性映射 -->
</resultMap>
```
然后,可以在子类的`resultMap`中引用并扩展基本的`resultMap`:
```xml
<resultMap id="ExtendedResultMap" type="com.example.ExtendedEntity" extends="BaseResultMap">
<!-- 扩展属性映射 -->
</resultMap>
```
通过使用`extends`属性,子类的`resultMap`可以继承基本的`resultMap`,并在此基础上添加或修改属性映射规则。
需要注意的是,这里的继承是在MyBatis的配置文件中实现的,并不是Java类的继承关系。