[mybatis]select_resultMap_自定义结果集映射规则

Posted 唐火

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[mybatis]select_resultMap_自定义结果集映射规则相关的知识,希望对你有一定的参考价值。

resultMap

  • 自定义某个javaBean的封装规则
    • type:自定义规则的Java类型
    • id:唯一id方便引用
  • 指定主键列的封装规则
    • id:定义主键底层会有优化
    • column:指定哪一列
    • property:指定对应的javaBean属性
public interface EmployeeMapperPlus 

    public Employee getEmpById(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">
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapperPlus">

    <resultMap id="MyEmp" type="com.atguigu.mybatis.bean.Employee">
        <!--        指定主键列的封装规则
                    column:指定哪一列
                    property:指定对应的javaBean属性
        -->

        <!--id定义主键底层会有优化-->
        <id column="id" property="id"></id>
        <!--        定义普通列封装规则-->
        <result column="last_name" property="lastName"></result>
        <!--        其他不指定的列会自动封装,我们只要写resultMap就把全部的映射规则都写上-->
        <result column="email" property="email"></result>
        <result column="gender" property="gender"></result>

    </resultMap>


    <!--    resultMap:自定义结果集映射规矩-->
    <!--    public Employee getEmpById(Integer id);-->
    <select id = "getEmpById" resultMap="MyEmp">

select * from tb1_employee where id = #id

    </select>


</mapper>

    @Test
    public void test03() throws IOException 
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try
        
            EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);

            Employee map = mapper.getEmpById(1);

            System.out.println(map);

        finally 

            sqlSession.close();

        
    

以上是关于[mybatis]select_resultMap_自定义结果集映射规则的主要内容,如果未能解决你的问题,请参考以下文章

[mybatis]映射文件_select_resultMap_关联查询_association分步查询&延迟加载

MyBatis学习总结-MyBatis快速入门的系列教程

Mybatis-Plus:了解Mybatis-Plus快速开始(Mybatis + Mybatis-Plus,Mybatis-Plus自动做了属性映射)

MyBatis1:MyBatis入门

MyBatis源码分析二MyBatis回顾

MyBatis1:MyBatis入门