MyBatis-Plus中如何使用ResultMap的方法示例

目录
  • 问题说明
  • 解决方法
  • 自定义@AutoResultMap注解

MyBatis-Plus (简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。

MyBatis-Plus对MyBatis基本零侵入,完全可以与MyBatis混合使用,这点很赞。

在涉及到关系型数据库增删查改的业务时,我比较喜欢用MyBatis-Plus,开发效率极高。具体的使用可以参考官网,或者自己上手摸索感受一下。

下面简单总结一下在MyBatis-Plus中如何使用ResultMap。

问题说明

先看个例子:

有如下两张表:

create table tb_book
(
    id     bigint primary key,
    name   varchar(32),
    author varchar(20)
);

create table tb_hero
(
    id      bigint primary key,
    name    varchar(32),
    age     int,
    skill   varchar(32),
    bid bigint
);

其中,tb_hero中的bid关联tb_book表的id。

下面先看Hero实体类的代码,如下:

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@TableName("tb_hero")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Hero {

    @TableId("id")
    private Long id;

    @TableField(value = "name", keepGlobalFormat = true)
    private String name;

    @TableField(value = "age", keepGlobalFormat = true)
    private Integer age;

    @TableField(value = "skill", keepGlobalFormat = true)
    private String skill;

    @TableField(value = "bid", keepGlobalFormat = true)
    private Long bookId;

    // *********************************
    // 数据库表中不存在以下字段(表join时会用到)
    // *********************************

    @TableField(value = "book_name", exist = false)
    private String bookName;

    @TableField(value = "author", exist = false)
    private String author;
}

注意了,我特地把tb_hero表中的bid字段映射成实体类Hero中的bookId属性。

测试BaseMapper中内置的insert()方法或者IService中的save()方法

MyBatis-Plus打印出的SQL为:

==> Preparing: INSERT INTO tb_hero ( id, "name", "age", "skill", "bid" ) VALUES ( ?, ?, ?, ?, ? )

==> Parameters: 1589788935356416(Long), 阿飞(String), 18(Integer), 天下第一快剑(String), 1(Long)

没毛病, MyBatis-Plus会根据@TableField指定的映射关系,生成对应的SQL。

测试BaseMapper中内置的selectById()方法或者IService中的getById()方法

MyBatis-Plus打印出的SQL为:

==> Preparing: SELECT id,"name","age","skill","bid" AS bookId FROM tb_hero WHERE id=?

==> Parameters: 1(Long)

也没毛病,可以看到生成的SELECT中把bid做了别名bookId。

测试自己写的SQL

比如现在我想连接tb_hero与tb_book这两张表,如下:

@Mapper

@Repository

public interface HeroMapper extends BaseMapper<Hero> {

    @Select({"SELECT tb_hero.*, tb_book.name as book_name, tb_book.author" +

            " FROM tb_hero" +

            " LEFT JOIN tb_book" +

            " ON tb_hero.bid = tb_book.id" +

            " ${ew.customSqlSegment}"})

    IPage<Hero> pageQueryHero(@Param(Constants.WRAPPER) Wrapper<Hero> queryWrapper,

                              Page<Hero> page);

}

查询MyBatis-Plus打印出的SQL为:

==> Preparing: SELECT tb_hero.*, tb_book.name AS book_name, tb_book.author FROM tb_hero LEFT JOIN tb_book ON tb_hero.bid = tb_book.id WHERE ("bid" = ?) ORDER BY id ASC LIMIT ? OFFSET ?

==> Parameters: 2(Long), 1(Long), 1(Long)

SQL没啥问题,过滤与分页也都正常,但是此时你会发现bookId属性为null,如下:

为什么呢?

调用BaseMapper中内置的selectById()方法并没有出现这种情况啊???

回过头来再对比一下在HeroMapper中自己定义的查询与MyBatis-Plus自带的selectById()有啥不同,还记得上面的刚刚的测试吗,生成的SQL有啥不同?

原来,MyBatis-Plus为BaseMapper中内置的方法生成SQL时,会把SELECT子句中bid做别名bookId,而自己写的查询MyBatis-Plus并不会帮你修改SELECT子句,也就导致bookId属性为null。

解决方法

方案一:表中的字段与实体类的属性严格保持一致(字段有下划线则属性用驼峰表示)

在这里就是tb_hero表中的bid字段映射成实体类Hero中的bid属性。这样当然可以解决问题,但不是本篇讲的重点。

方案二:把自己写的SQL中bid做别名bookId

方案三:使用@ResultMap,这是此篇的重点

在@TableName设置autoResultMap = true

@TableName(value = "tb_hero", autoResultMap = true)
public class Hero {
}

然后在自定义查询中添加@ResultMap注解,如下:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Mapper
@Repository

public interface HeroMapper extends BaseMapper<Hero> {

    @ResultMap("mybatis-plus_Hero")

    @Select({"SELECT tb_hero.*, tb_book.name as book_name, tb_book.author" +

            " FROM tb_hero" +

            " LEFT JOIN tb_book" +

            " ON tb_hero.bid = tb_book.id" +

            " ${ew.customSqlSegment}"})

    IPage<Hero> pageQueryHero(@Param(Constants.WRAPPER) Wrapper<Hero> queryWrapper,

                              Page<Hero> page);

}

这样,也能解决问题。

下面简单看下源码,@ResultMap("mybatis-plus_实体类名")怎么来的。

详情见: com.baomidou.mybatisplus.core.metadata.TableInfo#initResultMapIfNeed()

/**
 * 自动构建 resultMap 并注入(如果条件符合的话)
 */
void initResultMapIfNeed() {
    if (autoInitResultMap && null == resultMap) {
        String id = currentNamespace + DOT + MYBATIS_PLUS + UNDERSCORE + entityType.getSimpleName();
        List<ResultMapping> resultMappings = new ArrayList<>();
        if (havePK()) {
            ResultMapping idMapping = new ResultMapping.Builder(configuration, keyProperty, StringUtils.getTargetColumn(keyColumn), keyType)
                .flags(Collections.singletonList(ResultFlag.ID)).build();
            resultMappings.add(idMapping);
        }
        if (CollectionUtils.isNotEmpty(fieldList)) {
            fieldList.forEach(i -> resultMappings.add(i.getResultMapping(configuration)));
        }
        ResultMap resultMap = new ResultMap.Builder(configuration, id, entityType, resultMappings).build();
        configuration.addResultMap(resultMap);
        this.resultMap = id;
    }
}

注意看上面的字符串id的构成,你应该可以明白。

思考: 这种方式的ResultMap默认是强绑在一个@TableName上的,如果是某个聚合查询或者查询的结果并非对应一个真实的表怎么办呢?有没有更优雅的方式?

自定义@AutoResultMap注解

基于上面的思考,我做了下面简单的实现:

自定义@AutoResultMap注解

import java.lang.annotation.*;

/**
 * 使用@AutoResultMap注解的实体类
 * 自动生成{auto.mybatis-plus_类名}为id的resultMap
 * {@link MybatisPlusConfig#initAutoResultMap()}
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AutoResultMap {

}

动时扫描@AutoResultMap注解的实体类

package com.bytesfly.mybatis.config;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.bytesfly.mybatis.annotation.AutoResultMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * 可添加一些插件
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(basePackages = "com.bytesfly.mybatis.mapper")
@Slf4j
public class MybatisPlusConfig {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 分页插件(根据jdbcUrl识别出数据库类型, 自动选择适合该方言的分页插件)
     * 相关使用说明: https://baomidou.com/guide/page.html
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(DataSourceProperties dataSourceProperties) {

        String jdbcUrl = dataSourceProperties.getUrl();
        DbType dbType = JdbcUtils.getDbType(jdbcUrl);

        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(dbType));
        return interceptor;
    }

    /**
     * @AutoResultMap注解的实体类自动构建resultMap并注入
     */
    @PostConstruct
    public void initAutoResultMap() {
        try {
            log.info("--- start register @AutoResultMap ---");

            String namespace = "auto";

            String packageName = "com.bytesfly.mybatis.model.db.resultmap";
            Set<Class<?>> classes = ClassUtil.scanPackageByAnnotation(packageName, AutoResultMap.class);

            org.apache.ibatis.session.Configuration configuration = sqlSessionTemplate.getConfiguration();

            for (Class clazz : classes) {
                MapperBuilderAssistant assistant = new MapperBuilderAssistant(configuration, "");
                assistant.setCurrentNamespace(namespace);
                TableInfo tableInfo = TableInfoHelper.initTableInfo(assistant, clazz);

                if (!tableInfo.isAutoInitResultMap()) {
                    // 设置 tableInfo的autoInitResultMap属性 为 true
                    ReflectUtil.setFieldValue(tableInfo, "autoInitResultMap", true);
                    // 调用 tableInfo#initResultMapIfNeed() 方法,自动构建 resultMap 并注入
                    ReflectUtil.invoke(tableInfo, "initResultMapIfNeed");
                }
            }

            log.info("--- finish register @AutoResultMap ---");
        } catch (Throwable e) {
            log.error("initAutoResultMap error", e);
            System.exit(1);
        }
    }
}

关键代码其实没有几行,耐心看下应该不难懂。

使用@AutoResultMap注解

还是用例子来说明更直观。

下面是一个聚合查询:

@Mapper
@Repository
public interface BookMapper extends BaseMapper<Book> {
    @ResultMap("auto.mybatis-plus_BookAgg")
    @Select({"SELECT tb_book.id, max(tb_book.name) as name, array_agg(distinct tb_hero.id order by tb_hero.id asc) as hero_ids" +

            " FROM tb_hero" +

            " INNER JOIN tb_book" +

            " ON tb_hero.bid = tb_book.id" +

            " GROUP BY tb_book.id"})

    List<BookAgg> agg();
}

其中BookAgg的定义如下,在实体类上使用了@AutoResultMap注解:

@Getter
@Setter
@NoArgsConstructor
@AutoResultMap
public class BookAgg {
    @TableId("id")
    private Long bookId;
    @TableField("name")
    private String bookName;
    @TableField("hero_ids")
    private Object heroIds;
}

完整代码见: https://github.com/bytesfly/springboot-demo/tree/master/springboot-mybatis-plus

到此这篇关于MyBatis-Plus中如何使用ResultMap的方法示例的文章就介绍到这了,更多相关MyBatis-Plus使用ResultMap内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MyBatis中resultMap和resultType的区别详解

    总结 基本映射 :(resultType)使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功.(数据库,实体,查询字段,这些全部都得一一对应)高级映射 :(resultMap) 如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系.(高级映射,字段名称可以不一致,通过映射来实现 resultType和resultMap功能类似 ,都是返回对象信息 ,但是resultMap要更强大一些

  • MyBatis映射文件resultMap元素中使用多个association的方法

    现在有一张订单表t_stockorder,其拥有id.code.client_id.merchandise_id.merchandise_number.order_date.operator_id这些字段,其中client_id关联t_client表中code字段,merchandise_id关联t_merchandise表的code字段,operator_id关联t_employee表的code字段. 现在要通过SQL语句将订单表中t_stockorder的数据全部查询出来,SQL语句如下所示

  • Mybatis中强大的resultMap功能介绍

    前言 在Mybatis中,有一个强大的功能元素resultMap.当我们希望将JDBC ResultSets中的数据,转化为合理的Java对象时,你就能感受到它的非凡之处.正如其官方所述的那样: resultMap元素是 MyBatis 中最重要最强大的元素.它可以让你从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作.实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长

  • MyBatis中关于resultType和resultMap的区别介绍

    MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的(对应着我们的model对象中的实体),而resultMap则是对外部ResultMap的引用(提前定义了db和model之间的隐射key-->value关系),但是resultType跟resultMap不能同时存在. 在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值.

  • mybatis中resultMap 标签的使用教程

    MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注SQL本身,而不需要花费精力去处理例如注册驱动.创建connection.创建statement.手动设置参数.结果集检索等jdbc繁杂的过程代码. MyBatis特点: 1.开源的优秀持久层框架 2.SQL语句与代码分离 3.面向配置的编程 4.良好支持复杂数据映射 5.动态SQL resultMap 标签: 用来描述如何从数据库结果集中来加载对象 (敲黑板!!)主管数据库的字段和实体类属性的匹配,

  • MyBatis中的resultMap简要概述

    Mybatis简介 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录. Mybatis的功能架构分为三层(图片借用了百度百科): 1)       API接口层:提供给外部使用的接口API,开发人员通过这些本地API

  • MyBatis不同Mapper文件引用resultMap实例代码

    ClassesMapper.xml: <resultMap type="Classes" id="classesMap"> <id property="id" column="c_id" javaType="int"/> <result property="name" column="c_name" javaType="Stri

  • MyBatis-Plus中如何使用ResultMap的方法示例

    目录 问题说明 解决方法 自定义@AutoResultMap注解 MyBatis-Plus (简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发.提高效率而生. MyBatis-Plus对MyBatis基本零侵入,完全可以与MyBatis混合使用,这点很赞. 在涉及到关系型数据库增删查改的业务时,我比较喜欢用MyBatis-Plus,开发效率极高.具体的使用可以参考官网,或者自己上手摸索感受一下. 下面简单总结一下在MyBatis-Plus中如何使用R

  • logback中显示mybatis查询日志文件并写入的方法示例

    目录 在logback中显示mybatis查询日志 一.配置文件 二.定制包的日志level 三.通过logback-spring.xml文件 将操作数据库sql记录到日志文件中 网上看了很多篇文章关于如何配置mybatis的logback日志的,复杂的简单的都有,但是有用的没几个,耽误了很多时间.通过对logback的学习,以下方式是一定可行的,希望可以为大家节省点时间.通常我们可以通过如下配置将操作数据库的sql语句打印到控制台上,但是如何将这些sql语句记录到日志文件中方便我们查询问题呢?

  • oracle中decode函数的使用方法示例

    decode的几种用法 1:使用decode判断字符串是否一样 DECODE(value,if1,then1,if2,then2,if3,then3,...,else) 含义为 IF 条件=值1 THEN RETURN(value 1) ELSIF 条件=值2 THEN RETURN(value 2) ...... ELSIF 条件=值n THEN RETURN(value 3) ELSE RETURN(default) END IF sql测试 select empno,decode(empn

  • Java中生成唯一ID的方法示例

    有时我们不依赖于数据库中自动递增的字段产生唯一ID,比如多表同一字段需要统一一个唯一ID,这时就需要用程序来生成一个唯一的全局ID. UUID 从Java 5开始, UUID 类提供了一种生成唯一ID的简单方法.UUID是通用唯一识别码 (Universally Unique Identifier)的缩写,UUID来源于OSF(Open Software Foundation,开源软件基金会)的DCE(Distributed Computing Environment,分布式计算环境)规范.UU

  • C语言中可变参数的使用方法示例

    前言 在C语言程序编写中我们使用最多的函数一定包括printf以及很多类似的变形体.这个函数包含在C库函数中,定义为 int printf( const char* format, ...); 除了一个格式化字符串之外还可以输入多个可变参量,如: printf("%d",i); printf("%s",s); printf("the number is %d ,string is:%s", i, s); 格式化字符串的判断本章暂且不论,下面分析一

  • 在SpringBoot项目中的使用Swagger的方法示例

    一. 首先Swagger是什么? Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步.Swagger官方API文档:https://swagger.io/ 作用:   1. 接口的文档在线自动生成.   2. 功能测试. Swagger的主见介绍:    Swagger Codegen: 通过Codegen 可

  • java中的4种循环方法示例详情

    目录 java循环结构 1.while循环 2.do-while循环 3.for循环 4.java 增强for循环 java循环结构 顺序结构的程序语句只能 被执行一次.如果你要同样的操作执行多次,就需要使用循环结构. java中有三种主要的循环结构: while 循环 do...while 循环 for 循环 在java5中引入一种主要用于数组的增强型for循环. 1.while循环 while是最基本的循环,它的结构为: package com.example.lesson1; //whil

  • vue中的使用token的方法示例

    初始于登录页面 Home.vue <template> <div class="home"> </div> </template> <script> // @ is an alias to /src import HelloWorld from '@/components/HelloWorld.vue' import axios from 'axios'; export default { name: 'home', comp

  • Linux中gpio接口的使用方法示例

    前言 Linux内核中gpio是最简单,最常用的资源(和 interrupt ,dma,timer一样)驱动程序,应用程序都能够通过相应的接口使用gpio,gpio使用0-MAX_INT之间的整数标识,不能使用负数,gpio与硬件体系密切相关的,不过linux有一个框架处理gpio,能够使用统一的接口来操作gpio.在讲gpio核心(gpiolib.c)之前先来看看gpio是怎么使用的 使用gpio 使用gpio接口需要包含#include <linux/gpio.h> ,在驱动中使用延时函数

  • ASP.NET MVC4中使用Html.DropDownListFor的方法示例

    本文实例讲述了ASP.NET MVC4中使用Html.DropDownListFor的方法.分享给大家供大家参考,具体如下: 一.控制器部分: public ActionResult PageDetail() { var thisList = _sysDepartmentBll.GetAllDepartmentList();//数据源 //添加一条默认数据 var resultList = new List<SelectListItem> { new SelectListItem {Text

随机推荐