首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

MyBatis 整合 Spring 完整指南:從 MapperFactoryBean 到 MapperScannerConfigurer

     編輯:更多程式設計知識

    前言

    Spring 3 釋出時 MyBatis 3 尚未面世,官方無內建支援。MyBatis 社區提供 mybatis-spring 模組填補空白。本文系統講解整合核心組件:SqlSessionFactoryBean、MapperFactoryBean、MapperScannerConfigurer、SqlSessionTemplate,附完整 XML 與 Java 代碼範例。

    一、核心依賴

    • mybatis-spring-x.x.x.jar
    • mybatis-x.x.x.jar
    • Spring JDBC、Tx、Context 等模組
    • 資料庫驅動、連接池(如 DBCP、HikariCP)

    二、SqlSessionFactoryBean:整合入口

    封裝 SqlSessionFactoryBuilder,以 Spring Bean 方式暴露 SqlSessionFactory。

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:com/example/mapper/*.xml" />
        <property name="typeAliasesPackage" value="com.example.model" />
        <!-- 可選:configLocation, typeAliases, plugins, typeHandlersPackage, typeHandlers -->
    </bean>

    關鍵屬性:

    • dataSource(必填):資料源。
    • mapperLocations:Mapper XML 路徑,若與介面同目錄可省略。
    • typeAliasesPackage:實體類包路徑,自動以簡類名為別名。
    • configLocation:指定 MyBatis 總配置檔,後續屬性會覆蓋檔案內同名設定。

    三、MapperFactoryBean:單一 Mapper 註冊

    每個 Mapper 介面需定義一個 MapperFactoryBean,注入 sqlSessionFactory 與目標介面。

    <bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.example.mapper.BlogMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

    Service 中直接 @Resource BlogMapper blogMapper 注入使用。

    四、MapperScannerConfigurer:批量掃描註冊(推薦)

    避免逐個定義 Bean,自動掃描基包下所有介面註冊為 MapperFactoryBean。

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper" />
        <!-- 可選縮小範圍 -->
        <property name="markerInterface" value="com.example.mapper.SuperMapper" />
        <!-- 或 -->
        <property name="annotationClass" value="com.example.annotation.MyBatisMapper" />
        <!-- 多資料源指定 SessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    屬性說明:

    • basePackage(必填):掃描基包,多包用逗號/分號分隔。
    • markerInterface:僅註冊繼承此介面的 Mapper。
    • annotationClass:僅註冊標註此註解的 Mapper。
    • 兩者同時指定時取並集。
    • sqlSessionFactoryBeanName:多資料源場景指定 Bean 名稱(舊屬性 sqlSessionFactory、sqlSessionTemplate 已棄用)。

    五、完整 applicationContext.xml 範例

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="https://www.springframework.org/schema/beans"
           xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="https://www.springframework.org/schema/context"
           xsi:schemaLocation="https://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd
           https://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:component-scan base-package="com.example" />
        <context:property-placeholder location="classpath:jdbc.properties" />
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
        </bean>
    
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mapperLocations" value="classpath:com/example/mapper/*.xml" />
            <property name="typeAliasesPackage" value="com.example.model" />
        </bean>
    
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.example.mapper" />
            <property name="markerInterface" value="com.example.mapper.SuperMapper" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        </bean>
    </beans>

    六、SqlSessionTemplate:直接使用 SqlSession(可選)

    線程安全、自動綁定 Spring 事務、自動提交/關閉/回滾。

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

    DAO 中注入:

    @Repository
    public class BlogDaoImpl implements BlogDao {
        @Resource SqlSessionTemplate sqlSessionTemplate;
    
        public Blog find(int id) {
            return sqlSessionTemplate.selectOne("com.example.mapper.BlogMapper.selectBlog", id);
        }
        // insert/update/delete 同理
    }

    七、常見坑與最佳實踐

    • Mapper XML namespace 必須等於介面全限定名,否則綁定失敗。
    • 多資料源:定義多組 dataSource、sqlSessionFactory,配合 sqlSessionFactoryBeanName 分離掃描。
    • 事務管理:在 Service 層加 @Transactional,確保 SqlSessionTemplate 參與 Spring 事務。
    • 版本對應:MyBatis 3.5+ 對應 mybatis-spring 2.0+,Spring Boot 專案建議用 mybatis-spring-boot-starter 自動配置。

    結語

    掌握 SqlSessionFactoryBean + MapperScannerConfigurer 組合,即可輕鬆實現 MyBatis 與 Spring 無縫整合。實務上建議統一使用掃描器,搭配 Marker 介面或註解控制註冊範圍,保持配置簡潔、擴展靈活。

    1. 上一篇文章:
    2. 下一篇文章:
    Copyright © 程式碼之家 All Rights Reserved