• 还在使用mybatis的xml逐个映射字段?来看看mybatis返回Map(三种使用方式)


    SpringBoot+Mybatis返回Map(多种类型的map)

    缘起

    Mybatis自动映射了Java对象,属性–>数据库的表、字段,是一个半成品ORM(对象关系映射)框架,但是也会有一些业务场景,比如:多表联查,而过多的字段要在xml文件里面一一手动做映射,非常麻烦,那么我们可以直接在mybatis中返回一个map对象,字段什么的全都不用去手动定义(偷懒的一种方式_)。

    也可以返回不同类型的Map,种类先贴出来,后面解释

    • List<Map<String, String>>
      
      • 1
    • Map<String, <Map<String, String>>
      
      • 1
    • Map<String, ProductEntity>
      
      • 1

    实现

    用的技术:SpringBoot + mybatis plus + druid

    mybatis plus是mybatis 的增强版,可以快速通过Java代码构建sql语句,极大节省了开发效率,但是遇到多表联查之类的业务场景,还是要老老实实使用mybatis的xml文件构建sql语句。

    <properties>
        <java.version>1.8java.version>
        <commons-codec.version>1.10commons-codec.version>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <fast.version>1.2.78fast.version>
        <mybatis-plus>3.4.1mybatis-plus>
        <druid.version>1.1.14druid.version>
    properties>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    List>

    xml文件

    <select id="listProduct" resultType="map">
        select * from product
    select>
    
    • 1
    • 2
    • 3

    Mapper文件

    public interface ProductMapper extends BaseMapper<ProductEntity> {
        List<Map<String, Object>> listProduct();
    }
    
    • 1
    • 2
    • 3

    启动调用后报错

    Error attempting to get column 'created' from result set.  Cause: java.sql.SQLFeatureNotSupportedException\n; null; nested exception is java.sql.SQLFeatureNotSupportedException
    
    • 1

    是druid的版本太低了,调整一下版本,1.1.21及以上即可

    <druid.version>1.1.21druid.version>
    
    • 1

    看调试结果

    在这里插入图片描述

    解读:

    list中每个map对象,对应着表中的一条记录。

    Map>

    xml文件

    <select id="listProduct" resultType="map">
        select * from product
    select>
    
    • 1
    • 2
    • 3

    Mapper文件

    // 以 id列为key, 对应的一条记录为value
    @MapKey("id")
    Map<String, Map<String, Object>> listProduct();
    
    • 1
    • 2
    • 3

    调试
    在这里插入图片描述

    解读:

    外层map中以返回的id为key,整条记录作为value存入。内层map中key是每条记录中的字段名称,value是对应字段的值。

    Map

    xml文件

    <select id="listProduct" resultType="com.zlhy.calculation.entity.mybatis.ProductEntity">
        select * from product
    select>
    
    • 1
    • 2
    • 3

    Mapper文件

    @MapKey("id")
    Map<String, ProductEntity> listProduct();
    
    • 1
    • 2

    调试
    在这里插入图片描述

    解读:

    以返回的id作为key,整条记录作为实体类对象返回到Map中。

    温馨提示:

    以上返回map尽量用于不需要对map中返回的数据进行数据操作,否则用起来还是不太方便的(字段名也都是写死的,如果后续数据库中表字段要进行修改,那么改动起来有点麻烦),而如果涉及到单表查询或多表连查时如果对mapper返回的数据操作力度较小,可以使用返回map的方式。

  • 相关阅读:
    ​力扣解法汇总1260-二维网格迁移
    UE 交互草实现 不通过RT与距离场的方式
    Ubuntu 22.04.3 LTS中安装singularity
    【Python】Python基础
    [附源码]java毕业设计东软电子出版社管理系统
    无状态自动配置 DHCPv6无状态配置 DHCPv6有状态配置
    Sql优化总结!详细!(2021最新面试必问)
    【Redis】RedisTemplate序列化传输数据
    B48 - 基于51单片机的学生管理门禁系统设计
    二、T100应收管理之订金立帐
  • 原文地址:https://blog.csdn.net/weixin_45248492/article/details/126673154