MyBatis與Spring的整合第一步固然是導入各自依賴的Jar包,這裏強調一下要導入MyBatis提供的與Spring整合的插件包,mysql
若是用Maven項目的話在pom.xml文件中加入如下依賴即可:spring
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
整合的目的就是將MyBatis的所依賴的鏈接池,SqlSessiond的建立以及MyBatis的事務管理交給Spring去管理。sql
如下就是Spring的applicationContext.xml配置文件的內容:mybatis
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:context = "http://www.springframework.org/schema/context" xmlns:aop = "http://www.springframework.org/schema/aop" xmlns:tx = "http://www.springframework.org/schema/tx" xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 開啓Spring註解功能 --> <context:annotation-config /> <!-- 配置Spring註解掃描 --> <context:component-scan base-package = " at.flying.dao, at.flying.service " /> <!-- 開啓AspectJ 註解自動代理機制--> <aop:aspectj-autoproxy /> <!-- 開啓事務註解 --> <tx:annotation-driven /> <!--引入外部屬性文件--> <context:property-placeholder location = "classpath:db.properties" /> <!--配置C3P0鏈接池--> <bean id = "comboPooledDataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource"> <property name = "driverClass" value = "${mysql.driver}" /> <property name = "jdbcUrl" value = "${mysql.url}" /> <property name = "user" value = "${mysql.username}" /> <property name = "password" value = "${mysql.password}" /> </bean> <!--配置SQLSessionFactory工廠--> <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean"> <property name = "dataSource" ref = "comboPooledDataSource" /> <property name = "configLocation" value = "classpath:mybatis.xml" /> </bean> <!--配置事務管理器--> <bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name = "dataSource" ref = "comboPooledDataSource" /> </bean> </beans>
我事務管理採用的是註解的方式,因此這裏有必要強調一下,app
若是事務管理採用註解的方式的話,那麼在配置事務管理器的時候Bean的id必須指定爲 transactionManager,不然報錯。url
以下圖所示:spa
而後就是MyBatis的配置文件和映射文件,比較簡單就再也不闡述。插件
而後就是在寫DAO層的時候,本身的DAO類能夠(並不是必須)繼承 org.mybatis.spring.support.SqlSessionDaoSupport 這個類。代理
這相似於使用Hibernate時繼承HibernateDaoSupport同樣。code
以下圖所示: