MyBatis 2章 MyBatis与Spring整合

1、技术目标

  • 为项目添加Spring框架
  • 使用Spring在业务逻辑层对DAO完成依赖注入
  • 使用Spring在业务逻辑层进行事务处理

2、什么是Spring框架?

Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的。

框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,

同时为 J2EE 应用程序开发提供集成的框架

Spring框架由如下7个模块构成:

模块说明:

组成 Spring 框架的每个模块(或组件)都可以单独存在,或者与其他一个或多个模块联合实现。每个模块的功能如下:

  • 核心容器:核心容器提供 Spring 框架的基本功能。核心容器的主要组件是 BeanFactory,它是工厂模式的实现。BeanFactory 使用控制反转 (IOC) 模式将应用程序的配置和依赖性规范与实际的应用程序代码分开

  • Spring 上下文:Spring 上下文是一个配置文件,向 Spring 框架提供上下文信息。Spring 上下文包括企业服务,例如 JNDI、EJB、电子邮件、国际化、校验和调度功能

  • Spring AOP:通过配置管理特性,Spring AOP 模块直接将面向方面的编程功能集成到了 Spring 框架中。所以,可以很容易地使 Spring 框架管理的任何对象支持 AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP,不用依赖 EJB 组件,就可以将声明性事务管理集成到应用程序中

  • Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。Spring DAO 的面向 JDBC 的异常遵从通用的 DAO 异常层次结构

  • Spring ORM:Spring 框架插入了若干个 ORM 框架,从而提供了 ORM 的对象关系工具,其中包括 JDO、Hibernate 和 iBatis SQL Map。所有这些都遵从 Spring 的通用事务和 DAO 异常层次结构

  • Spring Web 模块:Web 上下文模块建立在应用程序上下文模块之上,为基于 Web 的应用程序提供了上下文。所以,Spring 框架支持与 Jakarta Struts 的集成。Web 模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作

  • Spring MVC 框架:MVC 框架是一个全功能的构建 Web 应用程序的 MVC 实现。通过策略接口,MVC 框架变成为高度可配置的,MVC 容纳了大量视图技术,其中包括 JSP、Velocity、Tiles、iText 和 POI

注意:关于Spring其他方面的应用细节不在本文讨论范围

3、使用准备

3.1)在项目中导入如下jar包(本文已提供下载):

aopalliance-1.0.jar

c3p0-0.9.1.2.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

commons-logging-1.1.1.jar

mybatis-spring-1.0.0.jar

org.springframework.aop-3.0.5.RELEASE.jar

org.springframework.asm-3.0.5.RELEASE.jar

org.springframework.beans-3.0.5.RELEASE.jar

org.springframework.context-3.0.5.RELEASE.jar

org.springframework.context.support-3.0.5.RELEASE.jar

org.springframework.core-3.0.5.RELEASE.jar

org.springframework.expression-3.0.5.RELEASE.jar

org.springframework.jdbc-3.0.5.RELEASE.jar

org.springframework.orm-3.0.5.RELEASE.jar

org.springframework.transaction-3.0.5.RELEASE.jar

org.springframework.web-3.0.5.RELEASE.jar

org.springframework.web.servlet-3.0.5.RELEASE.jar

3.2)创建如下包,放置业务逻辑代码:

com.xxx.service

com.xxx.service.impl

3.3)在src(类路径)下创建属性文件jdbc.properties,该属性文件用于保存

MySql连接参数以及C3P0连接池的相关配置,

内容如下:

#########MySql##############

jdbc.url=jdbc:mysql://localhost:3306/test

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.username=root

jdbc.password=123456

# Time to wait for an open connection before timing out

# (in milliseconds)

cpool.checkoutTimeout=5000

# Connection pool size

cpool.minPoolSize=5

cpool.maxPoolSize=20

# How long to keep unused connections around(in seconds)

# Note: MySQL times out idle connections after 8 hours(28,800 seconds)

# so ensure this value is below MySQL idle timeout

cpool.maxIdleTime=3600

# How long to hang on to excess unused connections after traffic spike

# (in seconds)

cpool.maxIdleTimeExcessConnections=1800

# Acquiring new connections is slow, so eagerly retrieve extra connections

# when current pool size is reached

cpool.acquireIncrement=5

3.4)修改src(类路径)下的MyBatis配置文件mybatis-config.xml只保留Aliases配置,如下:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <!DOCTYPE configuration 
  3.         PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
  4.         "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
  5.      
  6. <configuration> 
  7.     <settings> 
  8.         <!-- changes from the defaults --> 
  9.         <setting name="lazyLoadingEnabled" value="false" /> 
  10.     </settings> 
  11.     <typeAliases> 
  12.         <typeAlias alias="Film" type="com.xxx.pojo.Film"/> 
  13.     </typeAliases> 
  14. </configuration> 

3.5)在src下创建Spring配置文件applicationContext-mybatis.xml,该配置文件包含Spring整合MyBatis的相关配置,如下:

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:p="http://www.springframework.org/schema/p" 
  6.             xmlns:tx="http://www.springframework.org/schema/tx" 
  7.             xmlns:context="http://www.springframework.org/schema/context" 
  8.             xsi:schemaLocation=" 
  9.                 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
  10.                 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
  11.                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 
  12.          
  13.         <!-- Properties文件读取配置,base的properties --> 
  14.         <context:property-placeholder location="classpath:jdbc.properties"/> 
  15.          
  16.         <!-- JNDI获取数据源(使用c3p0连接池) --> 
  17.         <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" dependency-check="none"> 
  18.                     <property name="driverClass" value="${jdbc.driverClassName}" /> 
  19.                     <property name="jdbcUrl" value="${jdbc.url}" /> 
  20.                     <property name="user" value="${jdbc.username}" /> 
  21.                     <property name="password" value="${jdbc.password}" /> 
  22.                     <property name="autoCommitOnClose" value="true"/> 
  23.                     <property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/> 
  24.                     <property name="initialPoolSize" value="${cpool.minPoolSize}"/> 
  25.                     <property name="minPoolSize" value="${cpool.minPoolSize}"/> 
  26.                     <property name="maxPoolSize" value="${cpool.maxPoolSize}"/> 
  27.                     <property name="maxIdleTime" value="${cpool.maxIdleTime}"/> 
  28.                     <property name="acquireIncrement" value="${cpool.acquireIncrement}"/> 
  29.                     <property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/> 
  30.             </bean> 
  31.           
  32.          
  33.         <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 
  34.             <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
  35.                     <property name="dataSource" ref="dataSource" /> 
  36.             </bean> 
  37.  
  38.             <!-- (Annotation方式配置services)enable component scanning (beware that this does not enable mapper scanning!) -->     
  39.             <context:component-scan base-package="com.xxx.service" /> 
  40.  
  41.             <!-- enable autowire --> 
  42.             <context:annotation-config /> 
  43.  
  44.             <!-- enable transaction demarcation with annotations --> 
  45.             <tx:annotation-driven /> 
  46.  
  47.         <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean --> 
  48.         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
  49.             <property name="dataSource" ref="dataSource" /> 
  50.             <property name="configLocation" value="classpath:mybatis-config.xml" /> 
  51.         </bean> 
  52.  
  53.         <!-- scan for mappers and let them be autowired --> 
  54.         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 
  55.             <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper --> 
  56.             <property name="basePackage" value="com.xxx.dao" /> 
  57.         </bean> 
  58.     </beans> 

4、创建业务逻辑接口、实现类

4.1)com.xxx.service包下创建业务逻辑接口FilmService,代码如下:

Java代码  收藏代码
  1. package com.xxx.service;   
  2.    
  3. import java.util.List;   
  4. import org.springframework.transaction.annotation.Transactional;   
  5. import com.xxx.pojo.Film;   
  6.   
  7. /**
  8. * 影片信息业务逻辑接口
  9. * @author HotStrong
  10. *
  11. */   
  12. public interface FilmService {   
  13.       
  14.     /**
  15.      * 添加一部影片
  16.      * @param film
  17.      */   
  18.     @Transactional   
  19.     public void insertFilm(Film film);   
  20.        
  21.     /**
  22.      * 修改一部影片的信息
  23.      * @param film
  24.      */   
  25.     @Transactional   
  26.     public void updateFilm(Film film);   
  27.        
  28.     /**
  29.      * 通过影片编号删除一部影片
  30.      * @param filmId
  31.      */   
  32.     @Transactional   
  33.     public void deleteFilm(int filmId);   
  34.        
  35.     /**
  36.      * 通过影片编号获取一部影片
  37.      * @param filmId
  38.      * @return
  39.      */   
  40.     public Film getFilmById(int filmId);   
  41.       
  42.     /**
  43.      * 获取所有的影片
  44.      * @return
  45.      */   
  46.     public List<Film> getAllFilm();   
  47.        

 

4.2)com.xxx.service.impl包下创建业务逻辑接口实现类FilmServiceImpl,代码如下:

Java代码  收藏代码
  1. package com.xxx.service;   
  2.    
  3. import java.util.List;   
  4. import org.springframework.beans.factory.annotation.Autowired;   
  5. import com.xxx.dao.temp.FilmMapper;   
  6. import com.xxx.pojo.Film;   
  7.   
  8. /**
  9. * 影片信息业务逻辑接口实现类
  10. * @author HotStrong
  11. *
  12. */   
  13. public class FilmServiceImpl implements FilmService {   
  14.        
  15.     //注入影片Mapper   
  16.     @Autowired   
  17.     private FilmMapper mapper;   
  18.        
  19.     public void insertFilm(Film film) {   
  20.           
  21.         mapper.insertFilm(film);                   
  22.     }   
  23.    
  24.     public void deleteFilm(int filmId) {   
  25.            
  26.         mapper.deleteFilm(filmId);   
  27.     }   
  28.   
  29.     public void updateFilm(Film film) {   
  30.            
  31.         mapper.updateFilm(film);   
  32.     }   
  33.        
  34.     public Film getFilmById(int filmId) {   
  35.            
  36.         return mapper.getFilmById(filmId);   
  37.     }   
  38.       
  39.     public List<Film> getAllFilm() {   
  40.            
  41.         return mapper.getAllFilm();   
  42.            
  43.     }   
  44.    
  45. }  


5、src(类路径)下创建Spring配置文件applicationContext-services.xml,加入业务逻辑对象的配置

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.         xsi:schemaLocation=" 
  7.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
  8.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
  9.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
  10.          
  11.         <!-- 电影业务逻辑对象 --> 
  12.         <bean id="filmService" class="com.xxx.service.FilmServiceImpl"></bean>       
  13.          
  14. </beans> 

6、com.xxx.test包下创建测试类TestSpringMyBatis,对业务逻辑对象进行测试,代码如下:

Java代码  收藏代码
  1. package com.xxx.test;   
  2.  
  3. import java.util.List;   
  4. import junit.framework.TestCase;   
  5. import org.springframework.context.ApplicationContext;   
  6. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  7. import com.xxx.pojo.Film;   
  8. import com.xxx.service.FilmService;   
  9.   
  10. /**
  11. * 测试Spring整合MyBatis
  12. * @author HotStrong
  13. *
  14. */   
  15. public class TestSpringMyBatis extends TestCase {   
  16.        
  17.     //Spring整合MyBatis相关配置文件   
  18.     private String[] configFiles = {"applicationContext-mybatis.xml", "applicationContext-services.xml"};   
  19.     //创建Spring应用上下文   
  20.     private ApplicationContext context =  new ClassPathXmlApplicationContext(configFiles);   
  21.        
  22.     public void testFilm(){   
  23.            
  24.         //获取影片业务逻辑对象   
  25.         FilmService filmService = (FilmService)context.getBean("filmService");   
  26.            
  27.         try {   
  28.                
  29.             /*以下为影片业务逻辑操作*/   
  30.                
  31.             //1、添加一部影片   
  32.             Film film = new Film();   
  33.             film.setFname("功夫熊猫2");//设置片名   
  34.             //filmService.insertFilm(film);//添加影片   
  35.                
  36.             //2、修改影片信息   
  37.             //先获取待修改的影片信息   
  38.             film = filmService.getFilmById(12);//12为功夫熊猫2的影片编号   
  39.             //修改影片名称   
  40.             film.setFname("功夫熊猫3");   
  41.             //修改操作   
  42.             filmService.updateFilm(film);   
  43.                
  44.             //3、删除"功夫熊猫3",其编号为12   
  45.             filmService.deleteFilm(12);   
  46.                
  47.             List<Film> filmList = filmService.getAllFilm();   
  48.                
  49.             //4、显示所有电影信息   
  50.             for(Film filmObj : filmList){   
  51.                    
  52.                 System.out.println("电影ID:" + filmObj.getId() + " 电影名:" + filmObj.getFname());   
  53.             }   
  54.                
  55.         } catch (Exception e) {   
  56.             e.printStackTrace();   
  57.         }   
  58.           
  59.     }   
  60. }   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLAlchemy 是一个 SQL 工具包和对象关系映射(ORM)库,用于 Python 编程语言。它提供了一个高级的 SQL 工具和对象关系映射工具,允许开发者以 Python 类和对象的形式操作数据库,而无需编写大量的 SQL 语句。SQLAlchemy 建立在 DBAPI 之上,支持多种数据库后端,如 SQLite, MySQL, PostgreSQL 等。 SQLAlchemy 的核心功能: 对象关系映射(ORM): SQLAlchemy 允许开发者使用 Python 类来表示数据库表,使用类的实例表示表中的行。 开发者可以定义类之间的关系(如一对多、多对多),SQLAlchemy 会自动处理这些关系在数据库中的映射。 通过 ORM,开发者可以像操作 Python 对象一样操作数据库,这大大简化了数据库操作的复杂性。 表达式语言: SQLAlchemy 提供了一个丰富的 SQL 表达式语言,允许开发者以 Python 表达式的方式编写复杂的 SQL 查询。 表达式语言提供了对 SQL 语句的灵活控制,同时保持了代码的可读性和可维护性。 数据库引擎和连接池: SQLAlchemy 支持多种数据库后端,并且为每种后端提供了对应的数据库引擎。 它还提供了连接池管理功能,以优化数据库连接的创建、使用和释放。 会话管理: SQLAlchemy 使用会话(Session)来管理对象的持久化状态。 会话提供了一个工作单元(unit of work)和身份映射(identity map)的概念,使得对象的状态管理和查询更加高效。 事件系统: SQLAlchemy 提供了一个事件系统,允许开发者在 ORM 的各个生命周期阶段插入自定义的钩子函数。 这使得开发者可以在对象加载、修改、删除等操作时执行额外的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值