mybatis-puls中resultMap数据映射

 

resultType
resultType可以把查询结果封装到pojo类型中,但必须pojo类的属性名和查询到的数据库表的字段名一致。 
如果sql查询到的字段与pojo的属性名不一致,则需要使用resultMap将字段名和属性名对应起来,进行手动配置封装,将结果映射到pojo中

resultMap

resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。

数据库字段:user_id,

实体类字段:userId

需要手动配置设置resultMap

Mapper中基本查询语句

<!-- 查询所有的订单数据 -->
    <!-- resultMap:填入配置的resultMap标签的id值 -->
    <select id="queryOrderAll" resultMap="orderResultMap">
        SELECT id, user_id,
        number,
        createtime, note FROM `order`
    </select>

resultMap中字段映射

<!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
    <!-- id:设置ResultMap的id -->
    <resultMap type="order" id="orderResultMap">
        <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <id property="id" column="id" />

        <!-- 定义普通属性 -->
        <result property="userId" column="user_id" />
        <result property="number" column="number" />
        <result property="createtime" column="createtime" />
        <result property="note" column="note" />
    </resultMap>

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
MyBatis-Plus 是一个 MyBatis 的增强工具,它提供了一系列增强功能来简化 MyBatis 的使用。其之一就是提供了一个比 MyBatis 更加方便的结果映射方式,就是通过 `ResultMap`。 `ResultMap` 是 MyBatis 提供的结果映射器,它可以将数据库查询返回的结果映射成 Java 对象。MyBatis-Plus 的 `ResultMap` 功能就是在 MyBatis 的 `ResultMap` 基础上进行的增强。 在 MyBatis-Plus ,我们可以通过 `@TableName` 注解来指定实体类和数据库表的映射关系,然后使用 `@TableField` 注解来指定实体类的属性和数据库表的字段的映射关系。 使用 MyBatis-Plus 的 `ResultMap` 功能时,我们只需要在实体类定义一个 `ResultMap`,然后在查询语句使用该 `ResultMap` 即可将查询结果映射成 Java 对象。 以下是一个使用 MyBatis-Plus `ResultMap` 的示例: ```java @TableName("user") public class User { @TableId(value = "id", type = IdType.AUTO) private Long id; @TableField("username") private String username; @TableField("password") private String password; // getter 和 setter 省略 } // 定义 ResultMap private static final ResultMap USER_RESULT_MAP = new ResultMap.Builder(configuration, "userResultMap", User.class, new ArrayList<ResultMapping>()) .id(new ResultMapping.Builder(configuration, "id", "id", Long.class).build()) .result(new ResultMapping.Builder(configuration, "username", "username", String.class).build()) .result(new ResultMapping.Builder(configuration, "password", "password", String.class).build()) .build(); // 使用 ResultMap 查询 List<User> userList = sqlSession.selectList("com.example.mapper.UserMapper.selectUserList", null, new RowBounds(0, 10), USER_RESULT_MAP); ``` 在上面的示例,我们首先使用 `@TableName` 和 `@TableField` 注解指定了实体类和数据库表之间的映射关系。然后我们定义了一个 `ResultMap`,并在其指定了实体类的属性和数据库表的字段的映射关系。最后我们在查询语句使用该 `ResultMap` 将查询结果映射成 Java 对象。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值