MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。 MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的记录。
每一个 MyBatis 的应 用程序 都以一 个 SqlSessionFactory 对象的 实例为 核心。SqlSessionFactory 对 象 的 实 例 可 以 通 过 SqlSessionFactoryBuilder 对 象 来 获 得 。SqlSessionFactoryBuilder 对象可以通过 XML 配置文件,或从以往使用惯例中准备好的 Configuration 类实例中来构建 SqlSessionFactory 对象。
1.从xml中构建SqlSessionFactory
String resource = "org/mybatis/example/Configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); sqlMapper = new SqlSessionFactoryBuilder().build(reader); <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="BlogMapper.xml"/> </mappers> </configuration>
2.从sqlSessionFactory中获取sqlSession
SqlSession session = sqlMapper.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(); }<mapper namespace="BlogMapper"> <select id="selectBlog" parameterType="int" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper>
在命名空间"BlogMapper"中,它定义了一个名为"selectBlog"的映射语句,这样它允许你使用完全限定名"BlogMapper.selectBlog"来调用映射语句。
这个命名可以直接映射相同命名空间下的映射器类,使用一个名称,参数和返回值和已映射的查询语句都一样的方法即可。 使用第二种查询方式的优点:首先它不是基于文字的,那就更安全了。第二,如果你的IDE 有代码补全功能,那么你可以利用它来操纵已映射的 SQL 语句。第三,不需要强制类型转换,同时 BlogMapper 接口可以保持简洁,返回值类型很安全(参数类型也很安全)。
public interface BlogMapper {//这个可以这样写 @Select("SELECT * FROM blog WHERE id = #{id}") Blog selectBlog(int id); }
范围和生命周期:
1.SqlSessionFactoryBuilder 一旦你创建了 SqlSessionFactory 后,这个类就不需要存在了。因此 SqlSessionFactoryBuilder 实例的最佳范围是方法范围。 2.SqlSessionFactory
一旦被创建, SqlSessionFactory 实例应该在你的应用程序执行期间都存在。使用SqlSessionFactory 的最佳实践是在应用程序运行期间不要重复创建多次。这样的操作将被视为是非常糟糕的。因此 SqlSessionFactory 的最佳范围是应用范围。有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。然而这两种方法都不认为是最佳实践。这样的话,你可以考虑依赖注入容器,比如Spring。这样的框架允许你创建支持程序来管理单例 SqlSessionFactory 的生命周期。 3.SqlSession
每个线程都应该有它自己的 SqlSession 实例。SqlSession 的实例不能共享使用,它也是线程不安全的。因此最佳的范围是请求或方法范围。
4.SqlSessionTemplate:MyBatis提供的持久层访问模板化的工具,线程安全,可通过构造参数或依赖注入SqlSessionFactory实例。所以一个应用一个就够了。