自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

細(xì)說(shuō) Spring 整合 Mybatis

開(kāi)發(fā) 前端
要實(shí)現(xiàn)MyBatis與Spring的整合,很明顯需要這兩個(gè)框架的JAR包,但是只使用這兩個(gè)框架中所提供的JAR包是不夠的,還需要其他的JAR包來(lái)配合使用,整合時(shí)所需準(zhǔn)備的JAR包具體如下。

[[434252]]

GitHub:https://github.com/nateshao/ssm/tree/master/116-mybatis-spring

1. 整合環(huán)境搭建

“要實(shí)現(xiàn)MyBatis與Spring的整合,很明顯需要這兩個(gè)框架的JAR包,但是只使用這兩個(gè)框架中所提供的JAR包是不夠的,還需要其他的JAR包來(lái)配合使用,整合時(shí)所需準(zhǔn)備的JAR包具體如下。

Spring框架所需的JAR包

  1. <dependencies> 
  2.    <!-- AOP開(kāi)發(fā)使用的JAR --> 
  3.     <dependency> 
  4.         <groupId>aopalliance</groupId> 
  5.         <artifactId>aopalliance</artifactId> 
  6.         <version>1.0</version> 
  7.     </dependency> 
  8.  
  9.     <dependency> 
  10.         <groupId>org.aspectj</groupId> 
  11.         <artifactId>aspectjweaver</artifactId> 
  12.         <version>1.9.6</version> 
  13.     </dependency> 
  14.     <dependency> 
  15.         <groupId>org.springframework</groupId> 
  16.         <artifactId>spring-aop</artifactId> 
  17.         <version>5.3.8</version> 
  18.     </dependency> 
  19.     <dependency> 
  20.         <groupId>org.springframework</groupId> 
  21.         <artifactId>spring-aspects</artifactId> 
  22.         <version>5.3.7</version> 
  23.     </dependency> 
  24.     <!-- 4個(gè)核心模塊JAR --> 
  25.     <dependency> 
  26.         <groupId>org.springframework</groupId> 
  27.         <artifactId>spring-beans</artifactId> 
  28.         <version>5.3.8</version> 
  29.     </dependency> 
  30.     <dependency> 
  31.         <groupId>org.springframework</groupId> 
  32.         <artifactId>spring-context</artifactId> 
  33.         <version>5.3.8</version> 
  34.     </dependency> 
  35.     <dependency> 
  36.         <groupId>org.springframework</groupId> 
  37.         <artifactId>spring-core</artifactId> 
  38.         <version>5.3.8</version> 
  39.     </dependency> 
  40.  
  41.     <dependency> 
  42.         <groupId>org.springframework</groupId> 
  43.         <artifactId>spring-expression</artifactId> 
  44.         <version>5.3.8</version> 
  45.     </dependency> 
  46.     <!-- JDBC和事務(wù)的JAR --> 
  47.     <dependency> 
  48.         <groupId>org.springframework</groupId> 
  49.         <artifactId>spring-jdbc</artifactId> 
  50.         <version>5.3.8</version> 
  51.     </dependency> 
  52.     <dependency> 
  53.         <groupId>org.springframework</groupId> 
  54.         <artifactId>spring-tx</artifactId> 
  55.         <version>5.3.8</version> 
  56.     </dependency> 
  57.   <dependency> 
  58.             <groupId>commons-logging</groupId> 
  59.             <artifactId>commons-logging</artifactId> 
  60.             <version>1.2</version> 
  61.     </dependency> 
  62. </dependencies> 

 

MyBatis與Spring整合的中間JAR

  1. <!-- MyBatis與Spring整合的中間JAR   --> 
  2. <dependency> 
  3.     <groupId>org.mybatis</groupId> 
  4.     <artifactId>mybatis-spring</artifactId> 
  5.     <version>2.0.6</version> 
  6. </dependency> 

 

數(shù)據(jù)庫(kù)驅(qū)動(dòng)JAR(MySQL)

  1. <dependency> 
  2.     <groupId>mysql</groupId> 
  3.     <artifactId>mysql-connector-java</artifactId> 
  4.     <version>5.1.47</version> 
  5. </dependency> 

 

數(shù)據(jù)源所需JAR(DBCP)

  1. <dependency> 
  2.     <groupId>commons-dbcp</groupId> 
  3.     <artifactId>commons-dbcp</artifactId> 
  4.     <version>1.4</version> 
  5. </dependency> 
  6. <dependency> 
  7.     <groupId>commons-pool</groupId> 
  8.     <artifactId>commons-pool</artifactId> 
  9.     <version>1.6</version> 
  10. </dependency> 

 

編寫(xiě)配置文件

  • 創(chuàng)建項(xiàng)目116-mybatis-spring,引入maven包

  • 編寫(xiě)db.properties
  • 編寫(xiě)Spring配置文件applicationContext.xml
  • 編寫(xiě)MyBatis配置文件mybatis-config.xml
  • 引入log4j.properties

db.properties

  1. jdbc.driver=com.mysql.jdbc.Driver 
  2. jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false 
  3. jdbc.username=root 
  4. jdbc.password=123456 
  5. jdbc.maxTotal=30 
  6. jdbc.maxIdle=10 
  7. jdbc.initialSize=5 

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" 
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context" 
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.     http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  9.     http://www.springframework.org/schema/tx  
  10.     http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
  11.     http://www.springframework.org/schema/context  
  12.     http://www.springframework.org/schema/context/spring-context-4.3.xsd 
  13.     http://www.springframework.org/schema/aop  
  14.     http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> 
  15.     <!--讀取db.properties --> 
  16.     <context:property-placeholder location="classpath:db.properties"/> 
  17.     <!-- 配置數(shù)據(jù)源 --> 
  18.    <bean id="dataSource"  
  19.             class="org.apache.commons.dbcp2.BasicDataSource"
  20.         <!--數(shù)據(jù)庫(kù)驅(qū)動(dòng) --> 
  21.         <property name="driverClassName" value="${jdbc.driver}" /> 
  22.         <!--連接數(shù)據(jù)庫(kù)的url --> 
  23.         <property name="url" value="${jdbc.url}" /> 
  24.         <!--連接數(shù)據(jù)庫(kù)的用戶名 --> 
  25.         <property name="username" value="${jdbc.username}" /> 
  26.         <!--連接數(shù)據(jù)庫(kù)的密碼 --> 
  27.         <property name="password" value="${jdbc.password}" /> 
  28.         <!--最大連接數(shù) --> 
  29.         <property name="maxTotal" value="${jdbc.maxTotal}" /> 
  30.         <!--最大空閑連接  --> 
  31.         <property name="maxIdle" value="${jdbc.maxIdle}" /> 
  32.         <!--初始化連接數(shù)  --> 
  33.         <property name="initialSize" value="${jdbc.initialSize}" /> 
  34.    </bean> 
  35.    <!-- 事務(wù)管理器,依賴于數(shù)據(jù)源 -->  
  36.    <bean id="transactionManager" class= 
  37.      "org.springframework.jdbc.datasource.DataSourceTransactionManager"
  38.       <property name="dataSource" ref="dataSource" /> 
  39.    </bean>     
  40.     <!--開(kāi)啟事務(wù)注解 --> 
  41.    <tx:annotation-driven transaction-manager="transactionManager"/> 
  42.     <!--配置MyBatis工廠 --> 
  43.     <bean id="sqlSessionFactory"  
  44.             class="org.mybatis.spring.SqlSessionFactoryBean"
  45.          <!--注入數(shù)據(jù)源 --> 
  46.          <property name="dataSource" ref="dataSource" /> 
  47.          <!--指定核心配置文件位置 --> 
  48.           <property name="configLocation" value="classpath:mybatis-config.xml"/> 
  49.    </bean> 
  50.     
  51.    <!--實(shí)例化Dao --> 
  52.    <bean id="customerDao" class="com.nateshao.dao.impl.CustomerDaoImpl"
  53.    <!-- 注入SqlSessionFactory對(duì)象實(shí)例--> 
  54.         <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
  55.    </bean> 
  56.    <!-- Mapper代理開(kāi)發(fā)(基于MapperFactoryBean) --> 
  57.    <!-- <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
  58.        <property name="mapperInterface" value="com.nateshao.mapper.CustomerMapper" /> 
  59.        <property name="sqlSessionFactory" ref="sqlSessionFactory" />   
  60.    </bean> --> 
  61.    <!-- Mapper代理開(kāi)發(fā)(基于MapperScannerConfigurer) --> 
  62.    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  63.         <property name="basePackage" value="com.nateshao.mapper" /> 
  64.    </bean> 
  65.     
  66.    <!-- 開(kāi)啟掃描 -->  
  67.    <context:component-scan base-package="com.nateshao.service" /> 
  68.     
  69. </beans> 

 

 

 

 

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?> 
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-config.dtd"
  4. <configuration> 
  5.     <!--配置別名 --> 
  6.     <typeAliases> 
  7.         <package name="com.nateshao.po" /> 
  8.     </typeAliases> 
  9.     <!--配置Mapper的位置 --> 
  10.  <mappers>  
  11.        <mapper resource="mapper/CustomerMapper.xml" /> 
  12.        <!-- Mapper接口開(kāi)發(fā)方式 --> 
  13.     <mapper resource="mapper/CustomerMapperInterface.xml" /> 
  14.         
  15.  </mappers> 
  16. </configuration> 

 

 

 

log4j.properties

  1. Global logging configuration 
  2. log4j.rootLogger=ERROR, stdout 
  3. # MyBatis logging configuration... 
  4. log4j.logger.com.nateshao=DEBUG 
  5. # Console output... 
  6. log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
  7. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
  8. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n 

這樣一來(lái),環(huán)境加載文件就全了

2. 傳統(tǒng)DAO方式的開(kāi)發(fā)整合

“采用傳統(tǒng)DAO開(kāi)發(fā)方式進(jìn)行MyBatis與Spring框架的整合時(shí),可以使用mybatis-spring包中所提供的SqlSessionTemplate類或SqlSessionDaoSupport類來(lái)實(shí)現(xiàn)。

  • SqlSessionTemplate:是mybatis-spring的核心類,它負(fù)責(zé)管理MyBatis的SqlSession,調(diào)用MyBatis的SQL方法。當(dāng)調(diào)用SQL方法時(shí),SqlSessionTemplate將會(huì)保證使用的SqlSession和當(dāng)前Spring的事務(wù)是相關(guān)的。它還管理SqlSession的生命周期,包含必要的關(guān)閉、提交和回滾操作。
  • SqlSessionDaoSupport:是一個(gè)抽象支持類,它繼承了DaoSupport類,主要是作為DAO的基類來(lái)使用??梢酝ㄟ^(guò)SqlSessionDaoSupport類的getSqlSession()方法來(lái)獲取所需的SqlSession。

代碼實(shí)現(xiàn)

CustomerDao.java

  1. public interface CustomerDao { 
  2.     // 通過(guò)id查詢客戶 
  3.     public Customer findCustomerById(Integer id); 

CustomerDaoImpl.java

  1. public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao { 
  2.     // 通過(guò)id查詢客戶 
  3.     public Customer findCustomerById(Integer id) { 
  4.         return this.getSqlSession().selectOne("com.nateshao.po" 
  5.                 + ".CustomerMapper.findCustomerById", id); 
  6.     } 

CustomerMapperInterface.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
  3.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
  4. <mapper namespace="com.nateshao.po.CustomerMapper"
  5.    <!--根據(jù)id查詢客戶信息 --> 
  6.    <select id="findCustomerById" parameterType="Integer" 
  7.            resultType="customer"
  8.       select * from t_customer where id = #{id} 
  9.    </select
  10. </mapper> 

 

 

測(cè)試類 DaoTest.java

  1. package com.nateshao.test; 
  2.  
  3. import com.nateshao.dao.CustomerDao; 
  4. import com.nateshao.mapper.CustomerMapper; 
  5. import com.nateshao.po.Customer; 
  6. import org.junit.Test; 
  7. import org.springframework.context.ApplicationContext; 
  8. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  9.  
  10. /** 
  11.  * @date Created by 邵桐杰 on 2021/10/26 15:12 
  12.  * @微信公眾號(hào) 程序員千羽 
  13.  * @個(gè)人網(wǎng)站 www.nateshao.cn 
  14.  * @博客 https://nateshao.gitee.io 
  15.  * @GitHub https://github.com/nateshao 
  16.  * @Gitee https://gitee.com/nateshao 
  17.  * Description: 
  18.  */ 
  19. public class DaoTest { 
  20.     @Test 
  21.     public void findCustomerByIdDaoTest() { 
  22.         ApplicationContext act = 
  23.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  24.         // 根據(jù)容器中Bean的id來(lái)獲取指定的Bean 
  25.         CustomerDao customerDao = 
  26.                 (CustomerDao) act.getBean("customerDao"); 
  27. //      CustomerDao customerDao = act.getBean(CustomerDao.class); 
  28.         Customer customer = customerDao.findCustomerById(1); 
  29.         System.out.println(customer); 
  30.     } 
  31.  
  32.     @Test 
  33.     public void findCustomerByIdMapperTest() { 
  34.         ApplicationContext act = 
  35.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  36.         CustomerMapper customerMapper = act.getBean(CustomerMapper.class); 
  37.         Customer customer = customerMapper.findCustomerByIdOne(1); 
  38.         System.out.println(customer); 
  39.     } 

3. Mapper接口方式的開(kāi)發(fā)整合

“在MyBatis+Spring的項(xiàng)目中,雖然使用傳統(tǒng)的DAO開(kāi)發(fā)方式可以實(shí)現(xiàn)所需功能,但是采用這種方式在實(shí)現(xiàn)類中會(huì)出現(xiàn)大量的重復(fù)代碼,在方法中也需要指定映射文件中執(zhí)行語(yǔ)句的id,并且不能保證編寫(xiě)時(shí)id的正確性(運(yùn)行時(shí)才能知道)。為此,我們可以使用MyBatis提供的另外一種編程方式,即使用Mapper接口編程。

基于MapperFactoryBean的整合

“MapperFactoryBean是MyBatis-Spring團(tuán)隊(duì)提供的一個(gè)用于根據(jù)Mapper接口生成Mapper對(duì)象的類,該類在Spring配置文件中使用時(shí)可以配置以下參數(shù):

  • mapperInterface:用于指定接口;
  • SqlSessionFactory:用于指定SqlSessionFactory;
  • SqlSessionTemplate:用于指定SqlSessionTemplate。如果與SqlSessionFactory同時(shí)設(shè)定,則只會(huì)啟用SqlSessionTemplate。

注意!!!

“雖然使用Mapper接口編程的方式很簡(jiǎn)單,但是在具體使用時(shí)還是需要遵循一些規(guī)范。

  1. Mapper接口的名稱和對(duì)應(yīng)的Mapper.xml映射文件的名稱必須一致。
  2. Mapper.xml文件中的namespace與Mapper接口的類路徑相同。
  3. Mapper接口中的方法名和Mapper.xml中定義的每個(gè)執(zhí)行語(yǔ)句的id相同。
  4. Mapper接口中方法的輸入?yún)?shù)類型要和Mapper.xml中定義的每個(gè)sql的parameterType的類型相同。
  5. Mapper接口方法的輸出參數(shù)類型要和Mapper.xml中定義的每個(gè)sql的resultType的類型相同。

“在實(shí)際的項(xiàng)目中,DAO層會(huì)包含很多接口,如果每一個(gè)接口都在Spring配置文件中配置,不但會(huì)增加工作量,還會(huì)使得Spring配置文件非常臃腫。為此,可以采用自動(dòng)掃描的形式來(lái)配置MyBatis中的映射器——采用MapperScannerConfigurer類。

MapperScannerConfigurer類在Spring配置文件中可以配置以下屬性:

  • basePackage:指定映射接口文件所在的包路徑,當(dāng)需要掃描多個(gè)包時(shí)可以使用分號(hào)或逗號(hào)作為分隔符。指定包路徑后,會(huì)掃描該包及其子包中的所有文件。
  • annotationClass:指定了要掃描的注解名稱,只有被注解標(biāo)識(shí)的類才會(huì)被配置為映射器。
  • sqlSessionFactoryBeanName:指定在Spring中定義的SqlSessionFactory的Bean名稱。
  • sqlSessionTemplateBeanName:指定在Spring中定義的SqlSessionTemplate的Bean名稱。如果定義此屬性,則sqlSessionFactoryBeanName將不起作用。
  • markerInterface:指定創(chuàng)建映射器的接口。

MapperScannerConfigurer的使用非常簡(jiǎn)單,只需要在Spring的配置文件中編寫(xiě)如下代碼:

  1. <!-- Mapper代理開(kāi)發(fā)(基于MapperScannerConfigurer) --> 
  2. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  3.      <property name="basePackage" value="com.nateshao.mapper" /> 
  4. </bean> 

 

通常情況下,MapperScannerConfigurer在使用時(shí)只需通過(guò)basePackage屬性指定需要掃描的包即可,Spring會(huì)自動(dòng)的通過(guò)包中的接口來(lái)生成映射器。這使得開(kāi)發(fā)人員可以在編寫(xiě)很少代碼的情況下,完成對(duì)映射器的配置,從而提高開(kāi)發(fā)效率。

4. 測(cè)試事務(wù)

如何進(jìn)行事務(wù)測(cè)試?

在項(xiàng)目中,Service層既是處理業(yè)務(wù)的地方,又是管理數(shù)據(jù)庫(kù)事務(wù)的地方。要對(duì)事務(wù)進(jìn)行測(cè)試,首先需要?jiǎng)?chuàng)建Service層,并在Service層編寫(xiě)添加客戶操作的代碼;然后在添加操作的代碼后,有意的添加一段異常代碼(如int i = 1/0;)來(lái)模擬現(xiàn)實(shí)中的意外情況;最后編寫(xiě)測(cè)試方法,調(diào)用業(yè)務(wù)層的添加方法。這樣,程序在執(zhí)行到錯(cuò)誤代碼時(shí)就會(huì)出現(xiàn)異常。

  1. @Service 
  2. @Transactional 
  3. public class CustomerServiceImpl implements CustomerService { 
  4.     //注解注入CustomerMapper 
  5.     @Autowired 
  6.     private CustomerMapper customerMapper; 
  7.     //添加客戶 
  8.     public void addCustomer(Customer customer) { 
  9.         this.customerMapper.addCustomer(customer); 
  10.         int i=1/0; //模擬添加操作后系統(tǒng)突然出現(xiàn)的異常問(wèn)題 
  11.     } 

在沒(méi)有事務(wù)管理的情況下,即使出現(xiàn)了異常,數(shù)據(jù)也會(huì)被存儲(chǔ)到數(shù)據(jù)表中;如果添加了事務(wù)管理,并且事務(wù)管理的配置正確,那么在執(zhí)行上述操作時(shí),所添加的數(shù)據(jù)將不能夠插入到數(shù)據(jù)表中。

總結(jié)

這篇文章首先對(duì)MyBatis與Spring框架整合的環(huán)境搭建進(jìn)行了講解,

然后講解了使用傳統(tǒng)DAO方式的開(kāi)發(fā)整合,以及基于Mapper接口方式的開(kāi)發(fā)整合。

 

責(zé)任編輯:武曉燕 來(lái)源: 程序員千羽
相關(guān)推薦

2020-11-09 10:16:41

Mybatis

2022-11-15 08:10:23

SpringMyBatis底層

2017-05-12 15:47:15

Spring BootMybatis Ann Web

2009-06-19 10:00:37

Struts和Spri

2009-06-18 15:24:08

Spring OSGi

2016-12-14 09:03:34

springhibernate異常

2021-05-19 09:53:16

SpringbootMyBatisMySQL

2009-07-17 17:16:48

Spring iBAT

2009-07-14 14:41:33

Webwork與Spr

2009-06-01 10:28:03

SpringOSGi整合

2009-06-25 17:13:51

jBPM與Spring

2009-07-14 16:55:32

MyEclipse S

2023-06-07 08:08:37

MybatisSpringBoot

2009-08-11 09:47:01

Spring整合Str

2010-08-03 09:15:05

ScalaSpring

2022-12-23 08:28:42

策略模式算法

2021-06-07 08:39:58

SpringBootMyBatisMapper

2015-12-28 10:48:44

RedisSpring緩存實(shí)例

2017-10-17 15:14:33

Spring BooThymeleafWeb

2017-04-17 10:35:40

Spring BooRedis 操作
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)