定义接口:
package com.atChina.dao;
import com.atChina.bean.Employee;
public interface EmployeePlusMapper {
public Employee getEmpByDepnos(Integer depno);
}
sql配置文件
<?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">
<!-- namespace不能随便自定义了,应该是接口类的全限定名 -->
<mapper namespace="com.atChina.dao.EmployeePlusMapper">
<!-- resultMap标签自定义某个javaBean的封装规则,
type属性:自定义规则的Java类型
id属性: 唯一id,方便引用
-->
<resultMap type="com.atChina.bean.Employee" id="defineEmp">
<!-- id标签 指定主键列的封装规则
id 定义主键,底层会优化
column: 指定哪一列
property:指定对应的javaBean属性
-->
<id column="deptno" property="deptno" />
<!-- result标签定义普通列封装规则 -->
<result column="dname" property="dname" />
<!-- 其他不指定的字段会自动封装,
但我们只要写resultMap就尽量把全部的映射规则都写上 -->
<result column="loc" property="loc" />
</resultMap>
<!-- resultType="" resultMap=""只能有一个,不能同时设置这两个属性 -->
<select id="getEmpByDepnos" resultMap="defineEmp">
select * from depttest a where deptno = #{deptno}
</select>
</mapper>
测试方法:
@Test
public void test24() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
try{
// 命名空间.id,这样别的配置文件里有同名的id,程序也不报错
EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);
System.out.println(em.getClass()); // 动态代理类
Employee ee = em.getEmpByDepnos(10);
System.out.println(ee);
}finally{
// 关闭
openSession.close();
}
}