七、MyBatis自定义映射resultMap

简介: 七、MyBatis自定义映射resultMap

image.png

@[toc]

七、自定义映射resultMap

注意:下面两行表看看就行,实际案例只用了很少很少的属性进行练习。

image.png

image.png

7.1 resultMap处理字段和属性的映射关系

若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射

/**
     * 解决字段名和属性名不一致的情况:
     * a>为字段起别名,保持和属性名的一致
     * b>设置全局配置,将_自动映射为驼峰
     * <setting name="mapUnderscoreToCamelCase" value="true"/>
     * c>通过resultMap设置自定义的映射关系
     * <resultMap id="userResultMap" type="User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="password" column="password"></result>
        <result property="mobile" column="mobile"></result>
        <result property="gender" column="gender"></result>
        <result property="lastLoginIp" column="last_login_ip"></result>
    </resultMap>
     */
    @Test
    public void testGetUserById2(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
        System.out.println(mapper.getUserById2(4));
    }
User getUserById2(@Param("id") Integer id);

方式1:只设置resultType="User",通过as设置别名

<!--方式1:只设置resultType="User",通过as设置别名-->
<select id="getUserById2" resultType="User">
        select id,username,password,gender,mobile,last_login_ip as lastLoginIp from litemall.litemall_user where id = #{id}
</select>

方式2:设置全局配置,将_自动映射为驼峰

mybatis-config.xml

<settings>
        <!--将表中字段的下划线自动转换为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--方式2:设置全局配置,将_自动映射为驼峰<setting name="mapUnderscoreToCamelCase" value="true"/>-->
<select id="getUserById2" resultType="User">
        select id,username,password,gender,mobile,last_login_ip from litemall.litemall_user where id = #{id}
</select>

方式3:只设置resultMap="userResultMap

<!--
        resultMap:设置自定义映射关系
        id:唯一标识,不能重复
        type:设置映射关系中的实体类类型
        子标签:
        id:设置主键的映射关系
        result:设置普通字段的映射关系
        属性:
        property:设置映射关系中的属性名,必须是type属性所设置的实体类类型中的属性名
        column:设置映射关系中的字段名,必须是sql语句查询出的字段名
-->
<resultMap id="userResultMap" type="User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="password" column="password"></result>
        <result property="mobile" column="mobile"></result>
        <result property="gender" column="gender"></result>
        <result property="lastLoginIp" column="last_login_ip"></result>
</resultMap>

<!--方式3:只设置resultMap="userResultMap"-->
<select id="getUserById2" resultMap="userResultMap">
        select * from litemall.litemall_user where id = #{id}
</select>

若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性名符合Java的规则(使用驼峰)

此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系

  • 可以通过为字段起别名的方式,保证和实体类中的属性名保持一致

  • 可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可

以在查询表中数据时,自动将_类型的字段名转换为驼峰

例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName

7.2 多对一映射处理

User对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    //id
    private Integer id;
    //用户名称
    private String username;
    //用户密码
    private String password;
    //用户手机号码
    private String mobile;
    //性别
    private Integer gender;
    //最近一次登录IP地址
    private String lastLoginIp;
    private Address address;
}

Address对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Address {
    //id
    private Integer id;
    //用户名称
    private String name;
    //用户ID
    private Integer userId;
}

查询员工信息以及员工所对应的部门信息

级联方式处理映射关系

/**
     * 处理多对一的映射关系:
     * a>级联属性赋值
     * b>association
     * c>分步查询
     */
    @Test
    public void getUserAndAddressById(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper selectMapper = sqlSession.getMapper(SelectMapper.class);
        User user = selectMapper.getUserAndAddressById(4);
        System.out.println(user);
    }
User getUserAndAddressById(@Param("id") Integer id);
<resultMap id="userAndAddressResultMap" type="User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="password" column="password"></result>
        <result property="mobile" column="mobile"></result>
        <result property="gender" column="gender"></result>
        <result property="lastLoginIp" column="last_login_ip"></result>
        <result column="id" property="address.id"></result>
        <result column="name" property="address.name"></result>
        <result column="user_id" property="address.userId"></result>
</resultMap>
<!--方式1:级联方式处理映射关系-->
<select id="getUserAndAddressById" resultMap="userAndAddressResultMap">
        select litemall_user.*, litemall_address.* from litemall_user left join litemall_address on litemall_user.id = litemall_address.user_id where litemall_user.id = #{id}
</select>

使用association处理映射关系

注意:使用\<association>标签和property属性、javaType属性

/**
     * 处理多对一的映射关系:
     * a>级联属性赋值
     * b>association
     * c>分步查询
     */
    @Test
    public void getUserAndAddressById(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper selectMapper = sqlSession.getMapper(SelectMapper.class);
        User user = selectMapper.getUserAndAddressById(4);
        System.out.println(user);
    }
User getUserAndAddressById(@Param("id") Integer id);
<resultMap id="userAndAddressResultMap2" type="User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="password" column="password"></result>
        <result property="mobile" column="mobile"></result>
        <result property="gender" column="gender"></result>
        <result property="lastLoginIp" column="last_login_ip"></result>
        <association property="address" javaType="Address">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
            <result column="user_id" property="userId"></result>
        </association>
</resultMap>
<!--方式2:使用association处理映射关系-->
<select id="getUserAndAddressById" resultMap="userAndAddressResultMap2">
        select litemall_user.*, litemall_address.* from litemall_user left join litemall_address on litemall_user.id = litemall_address.user_id where litemall_user.id = #{id}
</select>

分步查询

  • 查用户表
/**
     * 处理多对一的映射关系:
     * a>级联属性赋值
     * b>association
     * c>分步查询
     */
    @Test
    public void getUserAndAddressById(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        SelectMapper selectMapper = sqlSession.getMapper(SelectMapper.class);
        User user = selectMapper.getUserById2(4);
        AddressMapper addressMapper = sqlSession.getMapper(AddressMapper.class);
        Address address = addressMapper.getAddressByUserId(user.getId());
        user.setAddress(address);
        System.out.println(user);
    }
User getUserById2(@Param("id") Integer id);
<resultMap id="userResultMap" type="User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="password" column="password"></result>
        <result property="mobile" column="mobile"></result>
        <result property="gender" column="gender"></result>
        <result property="lastLoginIp" column="last_login_ip"></result>
</resultMap>
<select id="getUserById2" resultMap="userResultMap">
        select * from litemall.litemall_user where id = #{id}
</select>
  • 查地址表
Address getAddressByUserId(@Param("userId") Integer userId);
<select id="getAddressByUserId" resultType="Address">
        select * from litemall_address where user_id = #{userId}
</select>

7.3 一对多映射处理

Address对象

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Address {
    //id
    private Integer id;
    //用户名称
    private String name;
    //用户ID
    private Integer userId;

    private List<User> userList = new ArrayList<>();
}

collection

注意:使用\<collection>标签和property属性、ofType属性

/**
     * 处理一对多的映射关系
     * a>collection
     * b>分步查询
     */
    @Test
    public void getAddressAndUserById(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        AddressMapper addressMapper = sqlSession.getMapper(AddressMapper.class);
        //collection
        Address address = addressMapper.getAddressAndUserById(1);
        System.out.println(address);
    }
Address getAddressAndUserById(@Param("id") Integer id);
<resultMap id="addresAndUsersResultMap" type="address">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="user_id" property="userId"></result>
        <!--ofType:设置collection标签所处理的集合属性中存储数据的类型-->
        <collection property="userList" ofType="User">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="password" column="password"></result>
            <result property="mobile" column="mobile"></result>
            <result property="gender" column="gender"></result>
            <result property="lastLoginIp" column="last_login_ip"></result>
        </collection>
    </resultMap>
    <select id="getAddressAndUserById" resultMap="addresAndUsersResultMap">
        select litemall_user.*, litemall_address.* from litemall_address  left JOIN litemall_user on litemall_user.id = litemall_address.user_id where litemall_address.id = #{id}
    </select>

分步查询

  • 查地址表
/**
     * 处理一对多的映射关系
     * a>collection
     * b>分步查询
     */
    @Test
    public void getAddressAndUserById(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        AddressMapper addressMapper = sqlSession.getMapper(AddressMapper.class);

        //分步查询
        Address address = addressMapper.getAddressById(1);
        SelectMapper selectMapper = sqlSession.getMapper(SelectMapper.class);
        User user = selectMapper.getUserById(address.getUserId());
        address.getUserList().add(user);
        System.out.println(address);
    }
Address getAddressById(@Param("id") Integer id);
<select id="getAddressById" resultType="Address">
        select * from litemall_address where id = #{id}
</select>
  • 查用户表
User getUserById(@Param("id") Integer id);
<select id="getUserById" resultType="User">
        select * from litemall_user where id = #{id}
</select>

分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:

  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载

  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)"

本人其他相关文章链接

1.一、MyBatis简介:MyBatis历史、MyBatis特性、和其它持久化层技术对比、Mybatis下载依赖包流程
2.二、搭建MyBatis采用xml方式,验证CRUD(增删改查操作)
3.三、MyBatis核心配置文件详解
4.四、MyBatis获取参数值的两种方式(重点)
5.五、MyBatis的增删改查模板(参数形式包括:String、对象、集合、数组、Map)
6.六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
7.七、MyBatis自定义映射resultMap
8.八、(了解即可)MyBatis懒加载(或者叫延迟加载)
9.九、MyBatis动态SQL
10.十、MyBatis的缓存
11.十一、MyBatis的逆向工程
12.十二、MyBatis分页插件

image.png

重要信息

image.png
image.png
image.png

目录
相关文章
|
8月前
|
SQL XML Java
8、Mybatis-Plus 分页插件、自定义分页
这篇文章介绍了Mybatis-Plus的分页功能,包括如何配置分页插件、使用Mybatis-Plus提供的Page对象进行分页查询,以及如何在XML中自定义分页SQL。文章通过具体的代码示例和测试结果,展示了分页插件的使用和自定义分页的方法。
8、Mybatis-Plus 分页插件、自定义分页
|
5月前
|
SQL 缓存 Java
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
本文详细介绍了MyBatis的各种常见用法MyBatis多级缓存、逆向工程、分页插件 包括获取参数值和结果的各种情况、自定义映射resultMap、动态SQL
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
|
7月前
|
SQL XML Java
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
文章介绍了MyBatis中高级查询的一对多和多对一映射处理,包括创建数据库表、抽象对应的实体类、使用resultMap中的association和collection标签进行映射处理,以及如何实现级联查询和分步查询。此外,还补充了延迟加载的设置和用法。
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
|
7月前
|
SQL XML Java
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
文章介绍了MyBatis的简单增删改查操作,包括创建数据表、实体类、配置文件、Mapper接口及其XML文件,并解释了`#{}`预编译参数和`@Param`注解的使用。同时,还涵盖了resultType与resultMap的区别,并提供了完整的代码实例和测试用例。
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
|
1月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
43 0
|
3月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
155 2
|
6月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
285 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
6月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
181 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
6月前
|
前端开发 Java Apache
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
本文详细讲解了如何整合Apache Shiro与Spring Boot项目,包括数据库准备、项目配置、实体类、Mapper、Service、Controller的创建和配置,以及Shiro的配置和使用。
1473 1
Springboot整合shiro,带你学会shiro,入门级别教程,由浅入深,完整代码案例,各位项目想加这个模块的人也可以看这个,又或者不会mybatis-plus的也可以看这个
|
7月前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理