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 version="1.0" encoding="UTF-8"?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <settings>
- <!-- changes from the defaults -->
- <setting name="lazyLoadingEnabled" value="false" />
- </settings>
- <typeAliases>
- <typeAlias alias="Film" type="com.xxx.pojo.Film"/>
- </typeAliases>
- </configuration>
3.5)在src下创建Spring配置文件applicationContext-mybatis.xml,该配置文件包含Spring整合MyBatis的相关配置,如下:
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- 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">
- <!-- Properties文件读取配置,base的properties -->
- <context:property-placeholder location="classpath:jdbc.properties"/>
- <!-- JNDI获取数据源(使用c3p0连接池) -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" dependency-check="none">
- <property name="driverClass" value="${jdbc.driverClassName}" />
- <property name="jdbcUrl" value="${jdbc.url}" />
- <property name="user" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <property name="autoCommitOnClose" value="true"/>
- <property name="checkoutTimeout" value="${cpool.checkoutTimeout}"/>
- <property name="initialPoolSize" value="${cpool.minPoolSize}"/>
- <property name="minPoolSize" value="${cpool.minPoolSize}"/>
- <property name="maxPoolSize" value="${cpool.maxPoolSize}"/>
- <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>
- <property name="acquireIncrement" value="${cpool.acquireIncrement}"/>
- <property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/>
- </bean>
- <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- </bean>
- <!-- (Annotation方式配置services)enable component scanning (beware that this does not enable mapper scanning!) -->
- <context:component-scan base-package="com.xxx.service" />
- <!-- enable autowire -->
- <context:annotation-config />
- <!-- enable transaction demarcation with annotations -->
- <tx:annotation-driven />
- <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="configLocation" value="classpath:mybatis-config.xml" />
- </bean>
- <!-- scan for mappers and let them be autowired -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <!-- Mapper接口所在包名,Spring会自动查找其下的Mapper -->
- <property name="basePackage" value="com.xxx.dao" />
- </bean>
- </beans>
4、创建业务逻辑接口、实现类
4.1)com.xxx.service包下创建业务逻辑接口FilmService,代码如下:
- package com.xxx.service;
- import java.util.List;
- import org.springframework.transaction.annotation.Transactional;
- import com.xxx.pojo.Film;
- /**
- * 影片信息业务逻辑接口
- * @author HotStrong
- *
- */
- public interface FilmService {
- /**
- * 添加一部影片
- * @param film
- */
- @Transactional
- public void insertFilm(Film film);
- /**
- * 修改一部影片的信息
- * @param film
- */
- @Transactional
- public void updateFilm(Film film);
- /**
- * 通过影片编号删除一部影片
- * @param filmId
- */
- @Transactional
- public void deleteFilm(int filmId);
- /**
- * 通过影片编号获取一部影片
- * @param filmId
- * @return
- */
- public Film getFilmById(int filmId);
- /**
- * 获取所有的影片
- * @return
- */
- public List<Film> getAllFilm();
- }
4.2)com.xxx.service.impl包下创建业务逻辑接口实现类FilmServiceImpl,代码如下:
- package com.xxx.service;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import com.xxx.dao.temp.FilmMapper;
- import com.xxx.pojo.Film;
- /**
- * 影片信息业务逻辑接口实现类
- * @author HotStrong
- *
- */
- public class FilmServiceImpl implements FilmService {
- //注入影片Mapper
- @Autowired
- private FilmMapper mapper;
- public void insertFilm(Film film) {
- mapper.insertFilm(film);
- }
- public void deleteFilm(int filmId) {
- mapper.deleteFilm(filmId);
- }
- public void updateFilm(Film film) {
- mapper.updateFilm(film);
- }
- public Film getFilmById(int filmId) {
- return mapper.getFilmById(filmId);
- }
- public List<Film> getAllFilm() {
- return mapper.getAllFilm();
- }
- }
5、src(类路径)下创建Spring配置文件applicationContext-services.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: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-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <!-- 电影业务逻辑对象 -->
- <bean id="filmService" class="com.xxx.service.FilmServiceImpl"></bean>
- </beans>
6、com.xxx.test包下创建测试类TestSpringMyBatis,对业务逻辑对象进行测试,代码如下:
- package com.xxx.test;
- import java.util.List;
- import junit.framework.TestCase;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.xxx.pojo.Film;
- import com.xxx.service.FilmService;
- /**
- * 测试Spring整合MyBatis
- * @author HotStrong
- *
- */
- public class TestSpringMyBatis extends TestCase {
- //Spring整合MyBatis相关配置文件
- private String[] configFiles = {"applicationContext-mybatis.xml", "applicationContext-services.xml"};
- //创建Spring应用上下文
- private ApplicationContext context = new ClassPathXmlApplicationContext(configFiles);
- public void testFilm(){
- //获取影片业务逻辑对象
- FilmService filmService = (FilmService)context.getBean("filmService");
- try {
- /*以下为影片业务逻辑操作*/
- //1、添加一部影片
- Film film = new Film();
- film.setFname("功夫熊猫2");//设置片名
- //filmService.insertFilm(film);//添加影片
- //2、修改影片信息
- //先获取待修改的影片信息
- film = filmService.getFilmById(12);//12为功夫熊猫2的影片编号
- //修改影片名称
- film.setFname("功夫熊猫3");
- //修改操作
- filmService.updateFilm(film);
- //3、删除"功夫熊猫3",其编号为12
- filmService.deleteFilm(12);
- List<Film> filmList = filmService.getAllFilm();
- //4、显示所有电影信息
- for(Film filmObj : filmList){
- System.out.println("电影ID:" + filmObj.getId() + " 电影名:" + filmObj.getFname());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }