sqlsession代表与数据库一次回话,访问一次数据库就是一次回话,sqlsession底层封装了对数据库curd的操作实现.
SqlSession提供select/insert/update/delete方法,在旧版本中使用使用SqlSession接口的这些方法,但是新版的Mybatis中就会建议使用Mapper接口的方法。映射器其实就是一个动态代理对象,进入到MapperMethod的execute方法就能简单找到SqlSession的删除、更新、查询、选择方法,从底层实现来说:通过动态代理技术,让接口跑起来,之后采用命令模式,最后还是采用了SqlSession的接口方法(getMapper()方法等到Mapper)执行SQL查询(也就是说Mapper接口方法的实现底层还是采用SqlSession接口方法实现的)
SqlSession session = sqlSessionFactory.openSession();try { Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);} finally { session.close();
SqlSession session = sqlSessionFactory.openSession();try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101);} finally { session.close();
上面一个是基于xml定义的,一个是基于注解定义的,mybatis全部特性都是利用xml映射语言来实现的。
?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select>
通过完全限定性类名找到同名的mapper中命名空间下的sql语句。
BlogMapper 这样的映射器类(Mapper class)
Mybatis官方手册建议通过mapper对象访问mybatis,因为使用mapper看起来更优雅
spring管理bean后,一个MapperFactoryBean对象拥有一个sqlSession对象。类型是org.mybatis.spring.SqlSessionTemplate
每个MapperFactoryBean对象初始化的时候,都会创建一个sqlSession,代码在MapperFactoryBean类的父类SqlSessionDaoSupport中,当spring向MapperFactoryBean对象中注入SqlSessionFactory时就创建了SqlSession:
重要:spring整合mybatis使用的sqlSession类型是org.mybatis.spring.SqlSessionTemplate,
【结论】spring整合mybatis后,非事务环境下,每次操作数据库都使用新的sqlSession对象。因此mybatis的一级缓存无法使用(一级缓存针对同一个sqlsession有效)