Spring 與 Mybatis 整合

參考官方文檔

在引入 Spring 和 Mybatis 的包之後,要將兩者整合,我們還需要 Spring-Mybatis 的包。使用這個類庫中的類, Spring 將會加載必要的 MyBatis 工廠類和 session 類。 這個類庫也提供一個簡單的方式來注入 MyBatis 數據映射器和 SqlSession 到業務層的 bean 中。

安裝

如果你使用 Maven,那麼在 pom.xml 中加入下面的代碼即可:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>x.x.x</version>
</dependency>

不同的版本對不同的 Spring 跟 Mybatis 版本要求不同,需要查看官方文檔的說明。

使用

要和 Spring 一起使用 MyBatis,我們需要在 Spring 配置文件中定義 sqlSessionFactory ,如

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

其中 dataSource 爲數據源,這可以是任意 的 DataSource,配置它就和配置其它 Spring 數據庫連接一樣。mapperLocations 爲 XML 映射文件的位置,如果你的映射文件與你的映射類放在一起,那麼 mapperLocations 可以忽略。

假設有有一個數據映射類如下:

public interface UserMapper {
  @Select("SELECT * FROM users WHERE id = #{userId}")
  User getUser(@Param("userId") String userId);
} 

那麼可以使用 MapperFactoryBean,像下面這樣來把接口加入到 Spring 中:

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

通常情況下我們有很多的映射類,沒有必要在 Spring 的 XML 配置文件中註冊所有的映射器。相反,你可以使用一個 MapperScannerConfigurer , 它 將 會 查 找 類 路 徑 下 的 映 射 器 並 自 動 將 它 們 創 建 成 MapperFactoryBean。

要創建 MapperScannerConfigurer,可以在 Spring 的配置中添加如下代碼:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="org.mybatis.spring.sample.mapper" />
</bean>

basePackage 屬性是讓你爲映射器接口文件設置基本的包路徑。 你可以使用分號或逗號 作爲分隔符設置多於一個的包路徑。每個映射器將會在指定的包路徑中遞歸地被搜索到。

事務

一個使用 MyBatis-Spring 的主要原因是它允許 MyBatis 參與到 Spring 的事務管理中。而 不是給 MyBatis 創建一個新的特定的事務管理器,MyBatis-Spring 利用了存在於 Spring 中的 DataSourceTransactionManager。

要 開 啓 Spring 的 事 務 處 理 , 在 Spring 的 XML 配 置 文 件 中 簡 單 創 建 一 個 DataSourceTransactionManager 對象:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>

要注意, 爲事務管理器指定的 DataSource 必須和用來創建 SqlSessionFactoryBean 的 是同一個數據源,否則事務管理器就無法工作了。

發佈了50 篇原創文章 · 獲贊 26 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章