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);

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

猜你喜欢

转载自blog.csdn.net/baiqi123456/article/details/123880358