不一致,那么用来接收查询出来的result对应的数据将会是Null,如果不使用resultMap,那么一般为了避免pojo对象对应的属性为Null,会采用SQL语句中的别名,将查询出的数据库中的字段as pojo对象属性,而且,resultMap支持延迟加载

但是为了避免sql语句看着 臃肿,所以就使用了resultMap

  简单使用

 1.    选定你要进行的resultMap映射的model,如下是我要进行映射的model,model=======>Category.java【进行resultMap的pojo类】

package com.atguigu.gulimall.product.vo;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Category {
    private Long catId;
    private String name;
    private Long parentCid;
    private Integer catLevel;
    private Integer status;
    private Integer sort;
    private String iconImage;
    private String userName;
    private String unit;
    private Integer count;
    private Integer isDelete;
}

             注意

                   不要在你要映射成resultMap的pojo类上加lombok的@Accessors(chain=true)的链式编程的注解,因为resultMap中的属性会报红【但是仍可使用】,如下图这样

                  

2.       在mapper.xml中编写resultMap,并在要使用的sql查询语句里,指定result标签为resultMap和其名称

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.atguigu.gulimall.product.dao.CategoryDao">
	<!-- 可根据自己的需求,是否要使用 -->
    <resultMap type="com.atguigu.gulimall.product.vo.Category" id="categoryMap">
        <result property="catId" column="cat_id"/>
        <result property="name" column="name"/>
        <result property="parentCid" column="parent_cid"/>
        <result property="catLevel" column="cat_level"/>
        <result property="status" column="show_status"/>
        <result property="sort" column="sort"/>
        <result property="iconImage" column="icon"/>
        <result property="count" column="product_count"/>
    </resultMap>
     <!--直接在sql查询返回的结果里指定resultMap-->
    <select id="queryByCid" parameterType="int" resultMap="categoryMap">
        select * from pms_category where cat_id = #{cId}
    </select>
</mapper>

         resultMap中各标签代表含义

type: resultMap最终映射的java对象,可以使用别名【如果使用resultMap实际返回的对象类型】
id:   resultMap的唯一标识【随便起】
result: 对普通名映射定义
property: type指定的返回的pojo对象中的属性名  写category里的属性名
column: 数据库中要查询出的字段【列名】           写要映射的数据库表里的字段名
property对应column形成数据库中字段和pojo属性对应关系

          注意

              如果此时resultMap在另外一个nameSpace里边,即其他的mapper文件里,那么在跨mapper使用时resultMap注明命名空间

3.  测试,直接运行项目

            如果在数据库里查询的字段个数少于或多于resultMap,那么依然能够映射成功,就映射对应的字段,因为名称映射不上或者pojo里没有的字段对应的属性,那么直接在返回的pojo 对象里返回null和没有该字段

                                      

到此这篇关于mybaits-plus的resultMap简单使用的文章就介绍到这了,更多相关mybaits-plus resultMap使用内容请搜索悠悠之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠悠之家!

点赞(525)

评论列表共有 0 条评论

立即
投稿
返回
顶部