【Mybatis】配置映射文件之resultMap元素和resultType元素

resultMap概述

resultMapMybatis映射文件中最重要最强大的元素。它描述如何从结果集中加载对象,主要作用是定义映射规则、级联的更新、定制类型转化器。它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来, 并在一些情形下允许你做一些 JDBC 不支持的事情。 实际上,在对复杂语句进行联合映射的时候,它很可能可以代替数千行的同等功能的代码。 resultMap的设计思想是,简单的语句不需要明确的结果映射,而复杂一点的语句只需要描述它们的关系就行了。

resultMap 子元素如下:

<resultMap>
        <constructor>
            <idArg/>
            <arg/>
        </constructor>
        <id/>
        <result/>
        <association property=""/>
        <collection property=""/>
        <discriminator javaType="">
            <case value=""></case>
        </discriminator>
</resultMap>
元素作用
constructor用于配置构造器方法,类实例化时来注入结果到构造方法
id列的主键
result配置POJO到数据库列名映射关系
association级联使用-代表一对一关系
collection级联使用-代表一对多关系
discriminator级联使用-鉴别器 根据实际选择实例,可以通过特定条件确定结果集

resultType元素

使用resultType进行输出映射,只有查询出来的列名和pojo(实体bean)中的属性名一致,该列才可以映射成功。简单来说也就是你的数据库字段和JavaBean里的字段名称必须一致才能映射成功。
例如 数据库字段:
在这里插入图片描述

使用pojo类存储结果

实体类:

public class User {
    private int id;
    private String name;
    private int age;
	//省略get set方法
}
public interface UserMapper {
   User slelectAll();
}

返回一条结果集

    <select id="slelectAll" resultType="com.lucas.mybatis.model.User">
        select  * from user where id = 2
    </select>

使用集合存储结果

resultType 也可以返回多条结果集

public interface UserMapper {
    List<User> slelectAll();
}

mapper文件

 <select id="slelectAll" resultType="com.lucas.mybatis.model.User">
     select  * from user
 </select>

使用Map存储结果集

 <select id="slelectAll" resultType="java.util.Map">
     select  * from user where id = 2
 </select>
public interface UserMapper {
   Map<String ,Object> slelectAll();
}
Map<String ,Object> map1 = userMapper.slelectAll();
 System.out.println(map1);

在这里插入图片描述

resultMap映射结果集

所以当我们JavaBean中的字段名和数据库字段名称有不同的时候,或者是多表查询的时候,一般会使用resultMap
mapper.xml文件修改如下

    <resultMap id="userResult" type="com.lucas.mybatis.model.User">
        <id property="id1" column="id"/>
        <result property="name1" column="name"/>
        <result property="age1" column="age1"/>
    </resultMap>
    <select id="slelectAll" resultMap="userResult">
        select  * from user where id = 2
    </select>

执行结果:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Teacher.Hu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值