成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

細說 Spring 整合 Mybatis

開發 前端
要實現MyBatis與Spring的整合,很明顯需要這兩個框架的JAR包,但是只使用這兩個框架中所提供的JAR包是不夠的,還需要其他的JAR包來配合使用,整合時所需準備的JAR包具體如下。

[[434252]]

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

1. 整合環境搭建

“要實現MyBatis與Spring的整合,很明顯需要這兩個框架的JAR包,但是只使用這兩個框架中所提供的JAR包是不夠的,還需要其他的JAR包來配合使用,整合時所需準備的JAR包具體如下。

Spring框架所需的JAR包

  1. <dependencies> 
  2.    <!-- AOP開發使用的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個核心模塊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和事務的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> 

 

數據庫驅動JAR(MySQL)

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

 

數據源所需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> 

 

編寫配置文件

  • 創建項目116-mybatis-spring,引入maven包

  • 編寫db.properties
  • 編寫Spring配置文件applicationContext.xml
  • 編寫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.     <!-- 配置數據源 --> 
  18.    <bean id="dataSource"  
  19.             class="org.apache.commons.dbcp2.BasicDataSource"
  20.         <!--數據庫驅動 --> 
  21.         <property name="driverClassName" value="${jdbc.driver}" /> 
  22.         <!--連接數據庫的url --> 
  23.         <property name="url" value="${jdbc.url}" /> 
  24.         <!--連接數據庫的用戶名 --> 
  25.         <property name="username" value="${jdbc.username}" /> 
  26.         <!--連接數據庫的密碼 --> 
  27.         <property name="password" value="${jdbc.password}" /> 
  28.         <!--最大連接數 --> 
  29.         <property name="maxTotal" value="${jdbc.maxTotal}" /> 
  30.         <!--最大空閑連接  --> 
  31.         <property name="maxIdle" value="${jdbc.maxIdle}" /> 
  32.         <!--初始化連接數  --> 
  33.         <property name="initialSize" value="${jdbc.initialSize}" /> 
  34.    </bean> 
  35.    <!-- 事務管理器,依賴于數據源 -->  
  36.    <bean id="transactionManager" class= 
  37.      "org.springframework.jdbc.datasource.DataSourceTransactionManager"
  38.       <property name="dataSource" ref="dataSource" /> 
  39.    </bean>     
  40.     <!--開啟事務注解 --> 
  41.    <tx:annotation-driven transaction-manager="transactionManager"/> 
  42.     <!--配置MyBatis工廠 --> 
  43.     <bean id="sqlSessionFactory"  
  44.             class="org.mybatis.spring.SqlSessionFactoryBean"
  45.          <!--注入數據源 --> 
  46.          <property name="dataSource" ref="dataSource" /> 
  47.          <!--指定核心配置文件位置 --> 
  48.           <property name="configLocation" value="classpath:mybatis-config.xml"/> 
  49.    </bean> 
  50.     
  51.    <!--實例化Dao --> 
  52.    <bean id="customerDao" class="com.nateshao.dao.impl.CustomerDaoImpl"
  53.    <!-- 注入SqlSessionFactory對象實例--> 
  54.         <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
  55.    </bean> 
  56.    <!-- Mapper代理開發(基于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代理開發(基于MapperScannerConfigurer) --> 
  62.    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
  63.         <property name="basePackage" value="com.nateshao.mapper" /> 
  64.    </bean> 
  65.     
  66.    <!-- 開啟掃描 -->  
  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接口開發方式 --> 
  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 

這樣一來,環境加載文件就全了

2. 傳統DAO方式的開發整合

“采用傳統DAO開發方式進行MyBatis與Spring框架的整合時,可以使用mybatis-spring包中所提供的SqlSessionTemplate類或SqlSessionDaoSupport類來實現。

  • SqlSessionTemplate:是mybatis-spring的核心類,它負責管理MyBatis的SqlSession,調用MyBatis的SQL方法。當調用SQL方法時,SqlSessionTemplate將會保證使用的SqlSession和當前Spring的事務是相關的。它還管理SqlSession的生命周期,包含必要的關閉、提交和回滾操作。
  • SqlSessionDaoSupport:是一個抽象支持類,它繼承了DaoSupport類,主要是作為DAO的基類來使用。可以通過SqlSessionDaoSupport類的getSqlSession()方法來獲取所需的SqlSession。

代碼實現

CustomerDao.java

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

CustomerDaoImpl.java

  1. public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao { 
  2.     // 通過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.    <!--根據id查詢客戶信息 --> 
  6.    <select id="findCustomerById" parameterType="Integer" 
  7.            resultType="customer"
  8.       select * from t_customer where id = #{id} 
  9.    </select
  10. </mapper> 

 

 

測試類 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.  * @微信公眾號 程序員千羽 
  13.  * @個人網站 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.         // 根據容器中Bean的id來獲取指定的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接口方式的開發整合

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

基于MapperFactoryBean的整合

“MapperFactoryBean是MyBatis-Spring團隊提供的一個用于根據Mapper接口生成Mapper對象的類,該類在Spring配置文件中使用時可以配置以下參數:

  • mapperInterface:用于指定接口;
  • SqlSessionFactory:用于指定SqlSessionFactory;
  • SqlSessionTemplate:用于指定SqlSessionTemplate。如果與SqlSessionFactory同時設定,則只會啟用SqlSessionTemplate。

注意!!!

“雖然使用Mapper接口編程的方式很簡單,但是在具體使用時還是需要遵循一些規范。

  1. Mapper接口的名稱和對應的Mapper.xml映射文件的名稱必須一致。
  2. Mapper.xml文件中的namespace與Mapper接口的類路徑相同。
  3. Mapper接口中的方法名和Mapper.xml中定義的每個執行語句的id相同。
  4. Mapper接口中方法的輸入參數類型要和Mapper.xml中定義的每個sql的parameterType的類型相同。
  5. Mapper接口方法的輸出參數類型要和Mapper.xml中定義的每個sql的resultType的類型相同。

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

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

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

MapperScannerConfigurer的使用非常簡單,只需要在Spring的配置文件中編寫如下代碼:

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

 

通常情況下,MapperScannerConfigurer在使用時只需通過basePackage屬性指定需要掃描的包即可,Spring會自動的通過包中的接口來生成映射器。這使得開發人員可以在編寫很少代碼的情況下,完成對映射器的配置,從而提高開發效率。

4. 測試事務

如何進行事務測試?

在項目中,Service層既是處理業務的地方,又是管理數據庫事務的地方。要對事務進行測試,首先需要創建Service層,并在Service層編寫添加客戶操作的代碼;然后在添加操作的代碼后,有意的添加一段異常代碼(如int i = 1/0;)來模擬現實中的意外情況;最后編寫測試方法,調用業務層的添加方法。這樣,程序在執行到錯誤代碼時就會出現異常。

  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; //模擬添加操作后系統突然出現的異常問題 
  11.     } 

在沒有事務管理的情況下,即使出現了異常,數據也會被存儲到數據表中;如果添加了事務管理,并且事務管理的配置正確,那么在執行上述操作時,所添加的數據將不能夠插入到數據表中。

總結

這篇文章首先對MyBatis與Spring框架整合的環境搭建進行了講解,

然后講解了使用傳統DAO方式的開發整合,以及基于Mapper接口方式的開發整合。

 

責任編輯:武曉燕 來源: 程序員千羽
相關推薦

2020-11-09 10:16:41

Mybatis

2022-11-15 08:10:23

SpringMyBatis底層

2017-05-12 15:47:15

Spring BootMybatis Ann Web

2016-12-14 09:03:34

springhibernate異常

2009-06-18 15:24:08

Spring OSGi

2009-06-19 10:00:37

Struts和Spri

2021-05-19 09:53:16

SpringbootMyBatisMySQL

2009-07-14 16:55:32

MyEclipse S

2009-06-25 17:13:51

jBPM與Spring

2009-06-01 10:28:03

SpringOSGi整合

2009-07-17 17:16:48

Spring iBAT

2009-07-14 14:41:33

Webwork與Spr

2009-08-11 09:47:01

Spring整合Str

2010-08-03 09:15:05

ScalaSpring

2022-12-23 08:28:42

策略模式算法

2025-05-09 07:20:02

Spring數據庫檢索

2021-06-07 08:39:58

SpringBootMyBatisMapper

2023-06-07 08:08:37

MybatisSpringBoot

2011-07-18 09:48:10

jQuery

2009-07-09 18:24:00

WebWork與Spr
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 91看片网| 日韩欧美精品 | 国产在线一区二区三区 | 欧美午夜视频 | 国产亚洲欧美另类一区二区三区 | 中文字幕 在线观看 | 日一日操一操 | 三区四区在线观看 | 国产精品高潮呻吟久久av黑人 | 欧美精品在线播放 | 久久久国产精品网站 | 99久久视频 | 久久久久国产精品人 | 日韩精品中文字幕一区二区三区 | 国产一级电影在线观看 | 99九色 | 成人免费看片 | 四虎永久免费影院 | 日韩精品免费在线观看 | 亚洲精品欧美一区二区三区 | 久久久久亚洲av毛片大全 | 国产成人99久久亚洲综合精品 | 日韩在线一区二区三区 | 91电影在线播放 | av在线天堂网| 国产精品污www一区二区三区 | 夜夜爽99久久国产综合精品女不卡 | 91精品国产91久久久久久密臀 | 日本精品一区二区 | 久久久av中文字幕 | 精品中文字幕久久 | 欧美一区二区三区大片 | 亚洲成人av一区二区 | 国产精品无码专区在线观看 | 日本成人在线观看网站 | 亚洲一区免费 | 国产日韩精品久久 | 亚洲国产一区二区视频 | 亚洲欧洲精品一区 | 黄色操视频| 欧美性另类 |