MyBatis custom mapping resultMap

MyBatis custom mapping resultMap


       When the field name of the database table is inconsistent with the attribute name in the entity class, you can set a custom mapping through resultMap. Below is a demo of resultMap.

Prepare

Database table
         t_student table
insert image description here
entity class object
         In order to reflect the characteristics of resultMap, the following classes are used as entity class objects.
insert image description here

MyBatis custom mapping resultMap

         Here is a demonstration by querying a piece of data (querying with id as a parameter).
Mapping interface

public interface TMapper {
    
    

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

}

map file

<?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>

Explanation
(1) select tag

         Write the query statement in the select tag.
         id: What is written is the method name in the mapped interface.
         resultMap: Writes the value of the id attribute in the resultMap tag.

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

(2) resultMap label

         The resultMap tag is used to set a custom map.
         id: Indicates the unique ID of the custom mapping.
         type: The type of the entity class to which the queried data is to be mapped.

Subtags of resultMap

         id: Set the mapping relationship of the primary key.
         result: Set the mapping relationship of common fields.
         property: Set the property name in the entity class in the mapping relationship.
         column: Set the field name in the table in the mapping relationship.

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

test

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

output result
insert image description here

Guess you like

Origin blog.csdn.net/baiqi123456/article/details/123880358