1.SqlSession操作SQL
创建了SqlSession后,可以通过SqlSession的方法来操作数据库
String statement = "org.poiuy.mybatis.intro.sqlsession.invoke.mapper.UserMapper.getUser"; //执行查询返回一个唯一user对象的sql MybatisUser user = session.selectOne(statement, 1);
Mapper配置文件配置中配置了调用的方法
<?xml version="1.0" encoding="UTF-8" ?><mapper namespace="org.poiuy.mybatis.intro.sqlsession.invoke.mapper.UserMapper"> <select id="getUser" parameterType="int" resultType="org.poiuy.mybatis.intro.sqlsession.invoke.domain.MybatisUser"> select * from mybatis_user where id=#{id} select>mapper>
2.SqlSession类调用方法操作数据库
SqlSession是一个接口,里面定义了一系列数据库操作的方法,
从SqlSession的创建过程中知道了其默认实现是DefaultSqlSession,进入DefaultSqlSession类中查看selectOne(String)方法
selectOne(String)会调用selectOne(String, Object)方法,传入的Object为null,返回泛型类型T
public T selectOne(String statement) { return this.selectOne(statement, (Object)null); }
在selectOne(String, Object)方法中,调用selectList(String, Object)获得一个List集合,如果集合元素个数为1,则正确返回,大于1的话会抛出TooManyResultsException异常,否则返回null
public T selectOne(String statement, Object parameter) { Listlist = this.selectList(statement, parameter); if (list.size() == 1) { return list.get(0); } else if (list.size() > 1) { throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); } else { return null; } }
在selectList(String, Object)方法中会调用selectList(String, Object, RowBounds)方法,RowBounds的值时RowBounds.DEFAULT,返回一个泛型的集合
public List selectList(String statement, Object parameter) { return this.selectList(statement, parameter, RowBounds.DEFAULT); }
RowBounds中DEFAULT调用无参构造方法,在构造方法中将offset赋值为0,limit为Integer的最大值,该参数是用来进行分页查询设置
public class RowBounds { public static final int NO_ROW_OFFSET = 0; public static final int NO_ROW_LIMIT = 2147483647; public static final RowBounds DEFAULT = new RowBounds(); private final int offset; private final int limit; public RowBounds() { this.offset = 0; this.limit = 2147483647; } ...}
最后查询逻辑实在selectList(String, Object, RowBounds)中实现
首先在Configuration中通过statement获得MappedStatement对象,
然后利用Executor的query方法获取List集合的结果
public List selectList(String statement, Object parameter, RowBounds rowBounds) { List var5; try { MappedStatement ms = this.configuration.getMappedStatement(statement); var5 = this.executor.query(ms, this.wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER); } catch (Exception var9) { throw ExceptionFactory.wrapException("Error querying database. Cause: " + var9, var9); } finally { ErrorContext.instance().reset(); } return var5; }
3.总结
SqlSession直接通过Mapper的namespace.id来进行操作时,首先通过namespace.id在配置文件对应的Configuration中获取对应的MappedStatement对象,然后使用Executor执行。SqlSession中实际上是通过Executor来处理数据库操作的