MyBatis 框架分层架构
MyBatis 简单案例:
public SqlSessionFactory getsqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
/**
* 1、获取 sqlSessionFactory 对象
*
* 2、获取 sqlSession 对象
*
* 3、获取接口的代理对象(MapperProxy)
*
* 4、执行增删改查方法
* @throws IOException
*/
@Test
public void test() throws IOException {
//1、获取 sqlSessionFactory
SqlSessionFactory sqlSessionFactory = getsqlSessionFactory();
//2、获取 sqlSession 实例,能直接执行已经映射的 SQL 语句
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//3、获取接口的实现类对象
/**
* 推荐使用
* 会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
*/
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
System.out.println(employeeMapper);
System.out.println(employeeMapper.getClass());
Employee emp = employeeMapper.getEmpById(1);
System.out.println(emp);
} finally {
sqlSession.close();
}
}
MyBatis-工作原理