什么是接口式编程?
在MyBatis中的体现为创建Mapper接口,然后将该接口引入到Mapper.xml的配置文件的命名空间中来进行动态绑定,使我们在使用SqlSession对象进行数据库操作时,进行传参类型约束。
接口中的方法名称一定要和配置文件中的id名称相同
例:接口
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
Mapper配置文件
<select id="getEmpById" resultType="com.mybatis.entity.Employee">
select id,last_name lastName,email,gander from employee where id = #{id}
</select>
改进测试类中的实现
//将创建SqlSessionFactory分离出来,每一次需要使用时,调用即可
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatisconfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
//接口型编程
@Test
public void test01() throws IOException {
//1、获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2、获取SqlSession对象
SqlSession openSession = sqlSessionFactory.openSession();
try {
//3、获取接口的实现类对象
//会为接口自动创建一个代理对象,代理对象去执行增删改查的方法
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee emp = mapper.getEmpById(1);
System.out.println(mapper.getClass());
System.out.println(emp);
}finally {
openSession.close();
}
}
从如下测试运行的结果中可以看出是MyBatis自动为我们创建了一个代理类
class com.sun.proxy.$Proxy9
Employee [id=1, lastName=MILLER, email=123@qq.com, gander=0]
步骤总结
1、接口式编程
- 原生: dao =====> daoImpl
- MyBatis dao =====> xxMapper.xml
2、SqlSession代表和数据库的一次对话,用完必须关闭
3、SqlSession和Connection一样,都不是线程安全的,每次使用都应该去获取新的对象
4、mapper接口没有实现类,但是mybatis会为这个接口生成一个代理对象
- (将接口和xml进行绑定)
- EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
5、两个重要的配置文件 - mybatis的全局配置文件:包含数据库连接信息,事务管理信息等……系统运行环境信息
- sql映射文件:保存了每一个sql语句的映射信息