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

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

猜你喜欢

转载自blog.csdn.net/huweiliyi/article/details/107907310