这个类可以通过SqlSessionFactoryBuilder获取
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);这个xml配置文件,设置了MyBatis的核心文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> // mapper里面映射的可能是xml文件或者注释过的包含SQL和mapping定义的接口类 </mappers> </configuration>这种提交方式有一些限制 , 一些复杂的映射关系还是会使用到XML文件 , 但是框架会帮我们自动完成这部分的XML文件的查找.
SqlSession基本上囊括了所有的数据库操作命令. 可以通过以下方式直接和数据库交互了(这是旧版本的):
SqlSession session = sqlSessionFactory.openSession(); try { Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); } finally { session.close(); }以下是一个新版本的(通过一个定义好的接口类BolgMapper.class来描述输入参数和返回值):
SqlSession session = sqlSessionFactory.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); } finally { session.close(); }namespace的值就是直接映射到一个具体的类. 但是上一节中涉及到两种写法 . 第二种写法的优势是避免的字符串的操作 ,并且对IDE是容易检查的或者说是友好的. 注意:
Namespace是必须的.Name Resolution: 为了减少输入 , MyBatis定义了一下name检索的简单规则(覆盖到了statement, result map , caches) 完整的全称类名如果检索到了是直接使用的(“com.mypackage.MyMapper.selectAllThings”)简写的名称可以用来引用全局唯一的入口. 如果有重复就会报错(“selectAllThings”)还有一个小技巧被映射的SQL语句不一定要在XML中定义. 也可以使用Java的注解来定义SQL package org.mybatis.example; public interface BlogMapper { @Select("SELECT * FROM blog WHERE id = #{id}") Blog selectBlog(int id); }注意: 依赖注入框架中,能够创建线程安全的事务的SqlSession和mapper,所以可以任意注入到自己使用的Bean中. 可以不考虑生命周期的问题. 可以参考MyBatis-Spring来了解依赖注入框架中的MyBatis.
最佳的使用范围是”方法”级别.可以通过Builder创建很多个SqlSessionFactory,但是不建议这样做.
一旦被创建了 , 应该和整个应用一同存在,即”应用”级别. 介乎没有情况需要去recreate它. 最简单的实现方法就是实现单例模式.
每个线程都应该拥有自己的SqlSession. 最好是”方法”级别的. 不要在任何静态域或者类的实例里面维护一个SqlSession的引用. 关闭SQLSesson非常重要. 要保证在final代码块中SqlSession被关闭了.以下是标准代码块
SqlSession session = sqlSessionFactory.openSession(); try { // do work } finally { session.close(); }应该<= SqlSession, 因为它是从SqlSession请求出来的.