mybatis-210719-02---映射文件_select_resultMap_自定义结果映射

mybatis-210719-02—映射文件_select_resultMap_自定义结果映射


EmployeeMapper.java

package com.bgy.mybatis.dao;

import com.bgy.mybatis.bean.Employee;

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

EmployeeMapper.xml

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

MybatisTest.java

package com.bgy.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import com.bgy.mybatis.bean.Employee;
import com.bgy.mybatis.dao.EmployeeMapper;

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

	/**
	 * 测试resultMap---自定义结果映射规则
	 * @throws IOException
	 */
	@Test
	public void test03() throws IOException{
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		try {
			EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
			
			Employee employee = mapper.getEmpById(1);
			
			System.out.println(employee);
		} finally {
			sqlSession.close();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值