MyBatis 是一款常用的持久层框架,使得程序能够以调用方法的方式执行某个指定的SQL,将执行SQL的底层逻辑进行封装。多数与Spring结合使用,本文讨论Spring如何整合Mybatis,首先看下Mybatis运行机制
1. Mybatis运行机制
1.1 Mybatis功能架构设计
Mybatis的功能架构分为三层:
(1)API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。
(2)数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。
(3)基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。
1.2 Mybatis运行方式
Mybatis支持两种方式执行SQL:Mapper接口和SqlSession,使用如下
public class MapperMain {
public static void main(String[] args) throws Exception {
File file = new File("/data/learncode/hobbit/src/main/resources/conf/mybatis/mybatis_config.xml");
InputStream inputStream = new FileInputStream(file);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
int id = 13;
// 方式1:Mapper接口发送SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println("Mapper接口发送:" + mapper.getById(id));
// 方式2:SqlSession发送SQL
UserEntity userEntity = sqlSession.selectOne("com.hobbit.mapper.UserMapper.getById", id);
System.out.println("SqlSession发送:" + userEntity);
}
}
复制代码
两种方式执行效果一致,如图
一般的话,比较推荐Mapper接口方法,因为手工写namespace和statementId极大增加了犯错误的概率,而且也降低了开发的效率。Mapper由MapperProxyFactory动态代理生成,封装了SqlSession。
2. Spring整合Mybatis要解决的问题
2.1 Mapper代理对象
重点关注下的Mapper动态代理对象,因为Spring整合Mybatis的核心目标是:把某个Mapper的代理对象作为一个bean放入Spring容器中,使得能够像使用一个普通bean一样去使用这个代理对象,比如能被@Autowire自动注入。常用如下通过Ioc容器把UserMapper注入了UserService:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public UserEntity queryUser(int id){
UserEntity use