concept
- MyBatis is a semi-automatic mapping framework. It is called semi-automatic because it needs to manually match the provided POJO, SQL, and mapping relationship, while Hibernate only needs to provide the POJO and mapping relationship.
Introductory case
Set up the environment
下载地址:
https://github.com/mybatis/mybatis-3/releases
创建项目,导入jar包
The basic composition of Mybatis
1) SqlSessionFactoryBuilder(构造器),
根据配置信息或代码来生成SqlSessionFactory(工厂接口)
2) SqlSessionFactory:来生成SqlSession
3) SqlSession:执行SQL并返回结果
4) SQLMapper:由一个Java接口和XML(或注解)构成
Build SqlSessionFactory
- Mapping file:
- Code:
Build SqlSession
- SqlSession two functions
- Get the mapper, let the mapper find the corresponding SQL through the namespace and method name, execute the SQL and return the result
- Directly execute SQL and return results through naming information
Mapper
映射器是由Java接口和XML文件(或注解)共同组成的。
作用如下:
1) 定义参数类型
2) 描述SQL语句
3) 定义查询结果和POJO的映射关系
4) 描述缓存
- Define an interface
- Define the corresponding mapping file
- Execute query:
Annotation generated mapper
life cycle
- After SqlSessionFactoryBuilder
creates SqlSessionFactory, its mission is completed - SqlSessionFactory
singleton - SqlSession
closes the session through finally
log4j and tools
1.引入log4j的配置文件,打印日志信息,查看执行的底层细节
2.创建SqlSessionFactoryUtil工具类,提供getSqlSession方法