SSM框架整合之Mybaits整合Spring

一、 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、結果
在這裏插入圖片描述

註釋那個異常代碼
在這裏插入圖片描述

結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章