1. 编写接口
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
2. 配置sql映射文件
- 将nameSpace指定为接口的全类名
- 将id指定为接口方法名
<mapper namespace="mybatis.dao.EmployeeMapper">
<!--
namespace: 名称空间;指定为接口的全类名
id: 唯一标识;指定为接口方法名
resultType: 返回类型
#{id}: 从传递过来的参数中取出id值
-->
<select id="getEmpById" resultType="mybatis.bean.Employee">
select id, last_name lastName, gender, email from tbl_employee where id = #{id}
</select>
</mapper>
3. 获取接口的实现类
使用SqlSession的getMapper方法获取接口的实现类时,SqlSession会为接口自动创建一个代理对象,让代理对象去执行增删改查。
@Test
public void test01() throws IOException {
// 1、获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2、获取sqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
try {
// 3、获取接口的实现类对象
// 会为接口自动创建一个代理对象,代理对象去执行增删改查
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
System.out.println(employee);
} finally {
openSession.close();
}
}
小结
- 接口式编程
原生: Dao =====> DaoImpl
mybatis: Mapper ====> xxMapper.xml - SqlSession代表和数据库的一次会话,用完必须关闭;
- SqlSession和connection一样都是非线程安全的,每次去使用都应该去获取新的对象。
- mapper接口没有实现类,但mybatis会为这个接口生成一个代理对象。(将接口和xml进行绑定)
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
- 两个重要的配置文件:
- mybatis的全局配置文件:包含数据库连接池信息,事务管理器信息等...系统运行环境信息
- sql映射文件:保存了每一个sql语句的映射信息