從XML中構建SqlSessionFactory
從XML檔案中構建SqlSessionFactory的執行個體非常簡單。這裡建議你使用類路徑下的資源檔來配置.
String resource = "org/mybatis/example/Configuration.xml"; Reader reader = Resources.getResourceAsReader(resource); sqlMapper = new SqlSessionFactoryBuilder().build(reader);
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"/> </mappers> </configuration>
當然,在XML設定檔中還有很多可以配置的,上面的樣本指出的則是最關鍵的部分。
從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介面可以保持簡潔,傳回值類型很安全(參數類型也很安全)。