十、MyBatis自定义映射resultMap

十、MyBatis自定义映射resultMap


       当数据库表的字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射。下面是resultMap的演示。

准备

数据库表
         t_student表
在这里插入图片描述
实体类对象
         为了体现出resultMap的特点,所以如下类作为实体类对象。
在这里插入图片描述

MyBatis自定义映射resultMap

         这里以通过查询一条数据进行演示(以id作为参数进行查询)。
映射接口

public interface TMapper {

    //通过id查询
    T selectStudentById(@Param("id")Integer id);

}

映射文件

<?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"><!--约束,约束不同xml中所写的标签也不同-->
<mapper namespace="com.xxx.mapper.TMapper"><!--接口-->

    <resultMap id="ttype" type="com.xxx.pojo.T">
        <id property="a" column="id"></id>
        <result property="b" column="name"></result>
        <result property="c" column="age"></result>
        <result property="d" column="sex"></result>
    </resultMap>
<!--    T selectStudentById(@Param("id")Integer id);-->
    <select id="selectStudentById" resultMap="ttype">
        select * from t_student where id=#{id}
    </select>


</mapper>

解释
(1)select标签

         select标签中写查询语句。
         id:所写的是映射接口中的方法名。
         resultMap:写的是resultMap标签中的id属性的值。

    <select id="selectStudentById" resultMap="ttype">
        select * from t_student where id=#{id}
    </select>

(2)resultMap标签

         resultMap标签中用于设置自定义映射。
         id:表示自定义映射的唯一标识。
         type:查询的数据要映射的实体类的类型。

resultMap的子标签

         id:设置主键的映射关系。
         result:设置普通字段的映射关系。
         property:设置映射关系中实体类中的属性名。
         column:设置映射关系中表中的字段名。

	<resultMap id="ttype" type="com.xxx.pojo.T">
        <id property="a" column="id"></id>
        <result property="b" column="name"></result>
        <result property="c" column="age"></result>
        <result property="d" column="sex"></result>
    </resultMap>

测试

		/*省略获取MyBatis核心配置文件等*/
		//通过代理模式创建TMapper接口的代理实现类对象
        TMapper mapper = sqlSession.getMapper(TMapper.class);
		//通过id查询
        T t = mapper.selectStudentById(1);
		//输出查询结果
        System.out.println(t);

输出结果
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

齊 天 大 聖

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

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

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

打赏作者

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

抵扣说明:

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

余额充值