myBatis3之从SqlSessionFactory中获取SqlSession
----------
现在,我们已经知道如何获取SqlSessionFactory对象了,基于同样的启示,我们就可以获得SqlSession的实例了。SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法。你可以用SqlSession实例来直接执行已映射的SQL 语句。例如:
SqlSession session = sqlMapper.openSession(); try{ Blog blog = (Blog)session.selectOne("org.mybatis.example.BlogMapper.selectBlog",101); }finally{ session.close(); }
现在有一种更简洁的方法。使用合理描述参数和SQL语句返回值的接口(比如BlogMapper.class),这样现在就更简单,更安全的代码,没有容易发生的字符串文字和转换的错误。例如:
SqlSession session = sqlSessionFactory.openSession(); try { BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101); }finally{ session.close(); }
探究已映射的SQL语句
这里给出一个基于XML映射语句的示例,这些语句应该可以满足上述示例中SqlSession对象的调用。
<?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" parameterType="int" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper>
在命名空间“com.mybatis.example.BlogMapper”中,它定义了一个名为“selectBlog”的映射语句,这样它允许你使用完全限定名“org.mybatis.example.BlogMapper.selectBlog”来调用映射语句,我们下面示例中的写法也就是这样的。
Blog blog = (Blog)session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
但下面的调用更有优势:
映射接口对应映射xml文件的命令空间,接口方法对应映射xml文件中定义的SQL映射的ID。???????????
BlogMapper mapper = session.getMapper(BlogMapper.class); Blog blog = mapper.selectBlog(101);
首先它不是基于文字的,那就更安全了。第二,如果你的IDE有代码补全功能,那么你可以利用它来操纵已映射的SQL语句。第三,不需要强制类型转换,同时BlogMapper接口可以保持简洁,返回值类型很安全(参数类型也很安全);