文章目錄
一、 MyBatis 整合 Spring - 有Mapper 實現類
1、目錄結構(紅色部分是前面SSM框架整合之Mybatis
代碼新增或修改的部分)
2、所需jar包
3、CustomerMapperImpl.java
4、jdbc.properties
5、applicationContext.xml
<?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">
<!-- 讀取jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 創建DataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 最大連接數 -->
<property name="maxActive" value="10"/>
<!-- 最大空閒數 -->
<property name="maxIdle" value="5"/>
</bean>
<!-- 創建SqlSessionFactory對象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 關聯連接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加載sql映射文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 創建CustomerMapperImpl對象,注入SqlSessionFactory -->
<bean id="customerMapper" class="cn.sm1234.dao.impl.CustomerMapperImpl">
<!-- 關聯sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
6、MyBatisSpringTest測試類
7、結果
二、MyBatis 整合Spring - 沒有Mapper 實現類
1、刪除 CustomerMapperImpl 類
2、修改 applicationContext.xml
3、MyBatisSpringTest測試類
4、結果
三、 MyBatis 整合 Spring - Mapper 接口掃描(推薦)
1、修改 applicationContext.xml
2、MyBatisSpringTest測試類
3、結果
四、MyBatis 整合 Spring - 整合 JDBC 事務
原先沒有配置事務的的,在異常前執行的方法仍然會持久到數據庫,顯然不受事務控制。
1、目錄結構
2、修改 applicationContext.xml
3、CustomerService接口
4、CustomerServiceImpl.java
5、MyBatisSpringTest測試類
6、結果
註釋那個異常代碼
結果