[mybatis-spring]sqlSessionFactoryBean


在mybatis中,SqlSessionFactory由SqlSessionFactoryBuilder創建.

在mybatis-spring中,是由SqlSessionFactoryBean創建的.

1.創建

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

注意SqlSessionFactoryBean實現了Spring的FactoryBean接口 (see section 3.8 of the Spring documentation).

這意味着Spring最終創建的bean不是SqlSessionFactoryBean自身,

而是SqlSessionFactoryBean的getObject()方法的返回結果.(看Java等價代碼第二行)

在這種情況下,Spring會在程序啟動時為你創建一個SqlSessionFactory,並且將其以sqlSessionFactory 的名稱存儲.

等價的Java代碼如下:

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

通常在mybatis-spring的使用中,不需要直接使用SqlSessionFactoryBean或者對應的SqlSessionFactory.

Session factory會被注入到MapperFactoryBean或者其他繼承SqlSessionDaoSupport的DAO.

2.屬性.

唯一必須的一個屬性:JDBC 數據源.

常用的屬性有configLocation,用來指定Mybatis的配置XML文件.

只有當MyBatis配置需要更改時才需要使用.這時,通常還會選擇<settings> or <typeAliases>

  注意:這個配置不需要是一個完整的mybatis配置. Specifically,任何environments,dataSourcec transactionManager都會被忽略.

SqlSessionFactoryBean 使用設置的值來創建它自己的定制化mybatis environment.

#另一個需要配置文件的原因是:#

mybatis mapper XML 文件不是和mapper類 在同一個classpath 位置下.

這樣配置有兩個可選的方法.

  第一個是手動指定XML文件的classpath,使用mybatis配置文件的<mappers> 選項.

  //之前的寫法.

  第二個是使用factory bean的 mapperLocations 屬性.

The mapperLocations property takes a list of resource locations. 

這個屬性可以用來指定mybatis xml mapper 文件.

value可以辦好Ant-style pattern來加載某個目錄下的單所有文件,

or to recursively search all paths from a base location. 

(或者遞歸地搜索基位置下的所有路徑)

<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 包和其子包下的所有xml格式的mybatis mapper文件.

 

/*

One property that may be required in an environment with container managed transactions is transactionFactoryClass .

Please see the relevant section in the Transactions chapter.

In case you are using the multi-db feature you will need to set the databaseIdProvider property:

*/

mybatis-spring 1.3.0版本后,增加了configuration屬性,
可以將mybatis的配置文件省略,而將其配置內容放入該bean下的一個屬性中

<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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM