MyBatis Spring SqlSessionFactoryBean 配置

FrankYou發表於2018-03-15

在基本的 MyBatis 中,session 工廠可以使用 SqlSessionFactoryBuilder 來建立。而在 MyBatis-Spring 中,則使用 SqlSessionFactoryBean 來替代。

Setup

要建立工廠 bean,放置下面的程式碼在 Spring 的 XML 配置檔案中:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

要注意 SqlSessionFactoryBean 實現了 Spring 的 FactoryBean 介面(請參考 Spring 文 檔的 3.8 章節)這就說明了由 Spring 最終建立的 bean 不是 SqlSessionFactoryBean 本身, 。 而是工廠類的 getObject()返回的方法的結果。這種情況下,Spring 將會在應用啟動時為你 建立 SqlSessionFactory 物件,然後將它以 SqlSessionFactory 為名來儲存。在 Java 中, 相同的程式碼是:

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
SqlSessionFactory sessionFactory = factoryBean.getObject();

在一般的 MyBatis-Spring 用法中, 你不需要直接使用 SqlSessionFactoryBean 或和其對 應的 SqlSessionFactory。相反,session 工廠將會被注入到 MapperFactoryBean 或其它擴 展了 SqlSessionDaoSupport 的 DAO(Data Access Object,資料訪問物件,譯者注)中。

屬性

SqlSessionFactory 有一個單獨的必須屬性,就是 JDBC 的 dataSource。這可以是任意 的 DataSource,其配置應該和其它 Spring 資料庫連線是一樣的。

一個通用的屬性是 configLocation,它是用來指定 MyBatis 的 XML 配置檔案路徑的。 如果基本的 MyBatis 配置需要改變, 那麼這就是一個需要它的地方。 通常這會是<settings> 或<typeAliases>的部分。

要注意這個配置檔案不需要是一個完整的 MyBatis 配置。確切地說,任意環境,資料來源 和 MyBatis 的事務管理器都會被忽略。SqlSessionFactoryBean 會建立它自己的,使用這些 值定製 MyBatis 的 Environment 時是需要的。

如果 MyBatis 對映器 XML 檔案在和對映器類相同的路徑下不存在,那麼另外一個需要 配置檔案的原因就是它了。使用這個配置,有兩種選擇。第一是手動在 MyBatis 的 XML 配 置檔案中使用<mappers>部分來指定類路徑。第二是使用工廠 bean 的 mapperLocations 屬 性。

mapperLocations 屬性使用一個資源位置的 list。 這個屬性可以用來指定 MyBatis 的 XML 對映器檔案的位置。 它的值可以包含 Ant 樣式來載入一個目錄中所有檔案, 或者從基路徑下 遞迴搜尋所有路徑。比如:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath*:sample/config/mappers/**/*.xml" />
</bean>

這會從類路徑下載入在 sample.config.mappers 包和它的子包中所有的 MyBatis 對映器 XML 檔案。

在容器環境管理事務中,一個可能需要的屬性是 transactionFactoryClass。請參考 第四章(4.2 節)中來檢視有關部分。

NOTE Since 1.3.0, configuration property has been added. It can be specified a Configuration instance directly without MyBatis XML configuration file. For example:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configuration">
    <bean class="org.apache.ibatis.session.Configuration">
      <property name="mapUnderscoreToCamelCase" value="true"/>
    </bean>
  </property>
</bean>

 

相關文章