首页 > 其他 > 详细

Mybatis学习笔记7 - resultMap自定义结果集映射规则

时间:2019-02-03 17:15:21      阅读:177      评论:0      收藏:0      [点我收藏+]

1、resultMap自定义结果集映射规则

示例如下:

接口定义:
package com.mybatis.dao;

import com.mybatis.bean.Employee;

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
}

mapper定义:
<?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.mybatis.dao.EmployeeMapper">
    <!--
    自定义某个javaBean的封装规则
	type:自定义规则的Java类型
	id:唯一标示id,方便引用
	-->
    <resultMap id="EmpMap" type="com.mybatis.bean.Employee">
        <!--
        指定主键列的封装规则
		id定义主键会底层有优化;
		column:指定哪一列
		property:指定对应的javaBean属性
		-->
        <id column="id" property="id"/>
        <!-- 定义普通列封装规则 -->
        <result column="last_name" property="lastName"/>
        <!-- 其他不指定的列会自动封装:但是最好只要写resultMap就把全部的映射规则都写上。 -->
        <result column="email" property="email"/>
        <result column="gender" property="gender"/>
    </resultMap>
    <!--public Employee getEmpById(Integer id);-->
    <!-- resultMap:自定义结果集映射规则;  -->
    <select id="getEmpById" resultMap="EmpMap">
		select * from tbl_employee where id=#{id}
	</select>
</mapper>


测试代码:
package com.mybatis.demo;

import java.io.*;
import java.util.*;

import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test;

public class MyTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testResultMap() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession(true);
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpById(1);
            System.out.println(employee);
        } finally {
            openSession.close();
        }
    }
}

 

Mybatis学习笔记7 - resultMap自定义结果集映射规则

原文:https://www.cnblogs.com/xidian2014/p/10350651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!