MyBatis中使用ResultMap映射实体类

本文详细介绍了如何在MyBatis中使用ResultMap映射实体类与数据库字段,解决实体类属性与数据库表字段命名不一致的问题,通过具体步骤和代码示例,展示了从数据库表设计、实体类创建、配置映射关系到单元测试的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyBatis中使用ResultMap映射实体类

本文阐述了在MyBatis中使用ResultMap映射实体类的具体操作步骤,并包含详细的代码,

主要是学习过程中的笔记,版权所有,转载请注明出处

示例工程:mybatis-demo2

1、背景

1)我们在实际开发的过程中,往往会经常遇到实体类的属性和数据库表字段名称不一致的情况,

​ 例如:数据库字段是下划线方式的,而实体类一般是驼峰命名法

2)这时就需要使用ResultMap将数据库的字段与实体类进行映射

2、具体步骤

2.1、数据库表-使用MySql数据库

1)我们使用之前的订单信息表tb_order_info作为演示,数据库的字段采用下划线的方式进行命名,具体的建表语句如下

-- 订单信息表
create table tb_order_info(
	order_id			varchar(10)						not null comment '订单id',
	payment				decimal(18,2)	default 0.00		comment '支付金额',
	goods_name			varchar(256)	default ''			comment '商品名称',
	payment_type		char(1)			default	'1'			comment '支付类型 : 1-在线支付,2-货到付款',
	post_fee			decimal(18,2)	default 0.00		comment '邮费',
	status				char(1)			default '1'			comment '订单状态:1-未付款,2-已付款,3-未发货,4-已发货,5-交易成功,6-交易关闭',
	create_time			date comment '订单创建时间',
	constraint pk_order_id primary key(order_id)
) engine=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 comment '订单信息表';

2.2、新建数据库实体-OrderInfo

1)新建数据库实体类OrderInfo,将实体类的属性字段采用驼峰命名法,用以区别

  • OrderInfo
package com.iambest.study.entity;

import java.math.BigDecimal;
import java.util.Date;

/**
 *
 * 订单信息表的实体类<br/>
 *
 * @author zhangwei
 * @since 1.0.0
 * @version 1.0.0
 */
public class OrderInfo {

    private String orderId;
    private BigDecimal payment;
    private String goodsName;
    private String paymentType;
    private BigDecimal postFee;
    private String status;
    private Date createTime;

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public BigDecimal getPayment() {
        return payment;
    }

    public void setPayment(BigDecimal payment) {
        this.payment = payment;
    }

    public String getGoodsName() {
        return goodsName;
    }

    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }

    public String getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(String paymentType) {
        this.paymentType = paymentType;
    }

    public BigDecimal getPostFee() {
        return postFee;
    }

    public void setPostFee(BigDecimal postFee) {
        this.postFee = postFee;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "OrderInfo [orderId=" + orderId + ", payment=" + payment
                + ", goodsName=" + goodsName + ", paymentType=" + paymentType
                + ", postFee=" + postFee + ", status=" + status
                + ", createTime=" + createTime + "]";
    }
}

2.3、调整SqlMapper的配置

1)首先使用<resultMap>标签定义数据库字段和实体类的属性之间的映射关系

2)然后在执行sql查询时将返回结果指定为该resultMap即可

3)如下示例:

  • OrderInfoMapper.xml

    <!-- 定义基本映射 -->
    <resultMap id="baseResultMap" type="com.iambest.study.entity.OrderInfo">
        <result property="orderId" column="order_id" jdbcType="VARCHAR" javaType="string"></result>
        <result property="payment" column="payment" jdbcType="DECIMAL" javaType="java.math.BigDecimal"></result>
        <result property="goodsName" column="goods_name" jdbcType="VARCHAR" javaType="string"></result>
        <result property="paymentType" column="payment_type" jdbcType="VARCHAR" javaType="string"></result>
        <result property="postFee" column="post_fee" jdbcType="DECIMAL" javaType="java.math.BigDecimal"></result>
        <result property="status" column="status" jdbcType="VARCHAR" javaType="string"></result>
        <result property="createTime" column="create_time" jdbcType="DATE"></result>
    </resultMap>

    <!-- 定义所有的列 -->
    <sql id="baseColumn">order_id,payment,goods_name,payment_type,post_fee,status,create_time</sql>

    <!-- 根据id查询订单信息 -->
    <select id="selectOne" resultMap="baseResultMap" parameterType="string">
        select
        <include refid="baseColumn"/>
        from tb_order_info
        where order_id=#{order_id}
    </select>

2.4、Mapper接口

1)在Mapper接口中新增selectOne方法,返回结果为OrderInfo实体类

   /**
     *
     * 根据订单的ID查询订单的信息
     *
     * @param order_id
     * @return
     */
    public OrderInfo selectOne(String order_id);

2.5、编写单元测试并执行

2.5.1、单元测试代码

1)在单元测试中编写如下的代码:

   @Test
    public void testResultMap() throws IOException{
        String config = "config/SqlMapConfig-insert.xml";
        Reader reader = Resources.getResourceAsReader(config);
        // 创建Builder对象
        SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder();
        // 创建Factory对象
        SqlSessionFactory factory = sfb.build(reader);
        // 通过factory对象生成session对象
        SqlSession session = factory.openSession();
        // 获取到Mapper接口对象
        OrderInfoMapper mapper = session.getMapper(OrderInfoMapper.class);
        OrderInfo entity = mapper.selectOne("102000000");
        System.out.println(entity);
        session.close();
    }
2.5.2、执行单元测试

1)运行单元测试代码,控制台可以正确的输出查询出的数据,并且数据库的实体对象的各个属性都能争取的赋值,表示成功,如下图所示:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack_David

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值