2.1整合思路分析
用Spring对MyBatis进行整合,将使得采用MyBatis操作数据库更加方便和简单。由于Spring 3的开发在MyBatis 3官方发布前就结束了,Spring开发团队不想发布一个基于非发布版本的MyBatis的整合支持,因此Spring 3没有提供对MyBatis3的支持。为了使Spring 3支持MyBatis 3,MyBatis团队开发出整合类,让开发者直接在Spring中使用MyBatis。
2.2 Spring和MyBatis整合核心类的介绍
在使用MyBatis-Spring整合之前,我们需要先下载相应的整合JAR包。在MyBatis的官方网站( http://code.google.com/p/mybatis/)上,找到MyBatis Integration,下载整合需要的mybatis-spring-1.2.0-bundle.zip,下载并解压后的目录如下图所示。整合时,在工程中只要包含mybatis-spring-1.2.0.jar就可以了。
MyBatis-Spring包的目录结构
要在Spring中使用MyBatis,需要在Spring的配置文件中定义一些类。下面先了解一下这些核心类。
1. SqlSessionFactoryBean
在MyBatis中,SqlSessionFactory可以使用SqISessionFactoryBuilder来创建,而在MyBatis-Spring中,使用SqISessinFacotryBean来代替,可以直接在Spring通过配置文件的形式配置。
2.MapperFactoryBean
MapperFactoryBean实现了Spring的FactoryBean接口,通过mapperlnterface属性注入接口,将映射接口变成可以注射的Spring Bean。
3. SqlSessionTemplate
SqlSessinTemplate类负责管理MyBatis的SqlSession,调用MyBatis的SQL映射语句,轻松实现数据库的访问。SqlSessionTernplate是线程安全的。当调用SQL方法时,包括通过从映射器getMapper()方法返回的映射器的方法,SqlSessionTemplate会保证使用的SqlSession是和当前Spring事务相关联的。此外,它管理会话的生命周期,包括必要的关闭、提交和回滚操作。
2.3 开发环境
开发工具:myeclipse8.6.1
数据库:mysql5.5.23
服务器: tomcat6.0.37
框架版本: spring3.2.2+mybatis3.2.2
2.4 案例开发步骤
步骤一:在myeclipse8.6中新建web工程SMMvc,拷贝如下包到lib目下:
代码的目录结构如下图所示:
步骤二:编写web.xml 配置文件,代码如下:
=================================web.xml========================
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置统一错误处理页面start -->
<error-page>
<error-code>404</error-code>
<location>/Err404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/Err500.html</location>
</error-page>
<!-- 配置统一错误处理页面end -->
<!-- 配置登录验证过滤器start -->
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>com.wx.filters.LoginFilter</filter-class>
<!-- 不做拦截的请求-->
<init-param>
<param-name>exclusions</param-name>
<param-value>SMMvc/,.js,.gif,.jpg,.jpeg,.png,.css,.ico,
Login.jsp,Login.php,Register.jsp,register.php,CheckUser.php,
ShowOneUser.jsp,ShowResult.jsp,Trans.php,ShowOneUser.php,quit.php
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置登录验证过滤器end -->
<!--druid连接池监控 config start -->
<filter>
<filter-name>DruidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DruidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<!--http://localhost:8080/SMMvc/druid/index.html end-->
<!-- 配置spring mvc的字符集过滤 start-->
<filter>
<filter-name>encode</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring mvc的字符集过滤 end-->
<!--配置 springmvc前端控制器 start-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:configs/mvc/springmvc-dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
<!--配置 springmvc前端控制器 end-->
<!-- 加载log4jstart -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:configs/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 加载log4j end-->
<!-- 加载spring容器 start-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:configs/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载spring容器 end-->
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
================================================================
知识讲解:Spring需要启动容器才能为其他框架提供服务,由于Web应用程序的人口是被Web服务器控制的,所以,无法在main()方法中通过创建ClassPallXmIApplicationContext对象来启动Spring容器。Spring提供了一个监听器类org.springframework.web.context.ContextLoaderListener来解决这个问题。该监听器实现了ServletContextListener接口,可以在Web容器启动的时候初始化Spring容器。当然,前提是需要在web.xml中配置好这个监听器。具体请参见上面配置代码及相关的注释部分。
步骤三:建立mybatis核心配置文件,如下所示:
====================== mybatis-config.xml============================
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEconfiguration
PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"
"mybatis-3-config.dtd">
<configuration>
<!-- 别名配置 -->
<typeAliases>
<typeAliastype="com.wx.entitys.UserEntity"alias="userEntity"/>
<typeAliastype="com.wx.entitys.PageEntity"alias="conEntity"/>
<typeAliastype="com.wx.entitys.StudentEntity"alias="stuEntity"/>
<typeAliastype="com.wx.entitys.DeptEntity"alias="deptEntity"/>
<typeAliastype="com.wx.entitys.PageEntity"alias="pageEntity"/>
</typeAliases>
</configuration>
=====================================================================
步骤四:建立druid数据源的属性文件,如下所示:
========================= druidConfig.properties=====================
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/schooldb
username=root
password=123456
#配置监控统计拦截的filters,去掉后监控界面sql无法统计
filters=stat
#配置初始化大小
initialSize=6
#配置初始化最大连接数
maxActive=20
#配置最小空闲连接数
minIdle=3
#配置获取连接等待超时的时间,1分钟
maxWait=60000
#检测连接是否有效的SQL
validationQuery=SELECT 'x'
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testOnReturn=false
#启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true
maxPoolPreparedStatementPerConnectionSize=20
#对于长时间不使用的连接强制关闭
removeAbandoned=true
#超过30秒的空闲连接就可以被关闭了,单位是秒
removeAbandonedTimeout=30
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis=10000
#配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis=30000
=====================================================================
步骤五:建立log4j的属性文件,如下所示:
========================= log4j.properties=====================
log4j.rootLogger=INFO, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d[%t] %-5p [%c] %m%n
=====================================================================
步骤六:建立spring的核心配置文件,如下所示:
========================= applicationContext.xml=====================
<?xmlversion="1.0"encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 导入dao层和service层的bean配置 -->
<importresource="classpath:configs/spring/applicationContext-*.xml"/>
<!-- 加载druid数据源的属性文件 -->
<beanid="config"class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<propertyname="location">
<value>classpath:configs/druidConfig.properties</value>
</property>
</bean>
<!-- druid数据源的配置 -->
<beanid="druidDataSource"class="com.alibaba.druid.pool.DruidDataSource"init-method="init"destroy-method="close">
<propertyname="driverClassName"value="${driverClassName}"/>
<propertyname="url"value="${url}"/>
<propertyname="username"value="${username}"/>
<propertyname="password"value="${password}"/>
<propertyname="filters"value="${filters}"/>
<propertyname="initialSize"value="${initialSize}"/>
<propertyname="maxActive"value="${maxActive}"/>
<propertyname="minIdle"value="${minIdle}"/>
<propertyname="maxWait"value="${maxWait}"/>
<propertyname="validationQuery"value="${validationQuery}"/>
<propertyname="testWhileIdle"value="${testWhileIdle}"/>
<propertyname="testOnBorrow"value="${testOnBorrow}"/>
<propertyname="testOnReturn"value="${testOnReturn}"/>
<propertyname="maxPoolPreparedStatementPerConnectionSize"value="${maxPoolPreparedStatementPerConnectionSize}"/>
<propertyname="removeAbandoned"value="${removeAbandoned}"/>
<propertyname="removeAbandonedTimeout"value="${removeAbandonedTimeout}"/>
<propertyname="timeBetweenEvictionRunsMillis"value="${timeBetweenEvictionRunsMillis}"/>
<propertyname="minEvictableIdleTimeMillis"value="${minEvictableIdleTimeMillis}"/>
</bean>
<!-- 配置sessionFactory,即在这里整合mybatis-->
<beanid="sessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="druidDataSource"></property>
<propertyname="configLocation">
<value>classpath:configs/mybatis-config.xml</value>
</property>
<propertyname="mapperLocations">
<list>
<value>classpath:com/wx/entitys/*.xml</value>
</list>
</property>
</bean>
<!-- 提供执行增删改查的 sqlSessionTemplate对象,用于注入到dao层-->
<beanid="sqlSessionTemplate"class="org.mybatis.spring.SqlSessionTemplate">
<constructor-argname="sqlSessionFactory"ref="sessionFactory"></constructor-arg>
</bean>
<!-- 统一事务处理的配置start -->
<beanid="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="druidDataSource"></property>
</bean>
<tx:adviceid="txAdvise"transaction-manager="txManager">
<tx:attributes>
<tx:methodname="find*"read-only="true"/>
<tx:methodname="search*"read-only="true"/>
<tx:methodname="query*"read-only="true"/>
<tx:methodname="get*"read-only="true"/>
<tx:methodname="add*"propagation="REQUIRED"/>
<tx:methodname="save*"propagation="REQUIRED"/>
<tx:methodname="do*"propagation="REQUIRED"/>
<tx:methodname="update*"propagation="REQUIRED"/>
<tx:methodname="del*"propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcutexpression="execution(* com.wx.service.*.*(..))"id="myCut"/>
<aop:advisoradvice-ref="txAdvise"pointcut-ref="myCut"/>
</aop:config>
<!-- 统一事务处理的配置end -->
</beans>
=====================================================================
步骤七:编写dao层的配置文件applicationContext-dao.xml,如下所示:
===================== applicationContext-dao.xml====================
<?xmlversion="1.0"encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<beanid="userDao"class="com.wx.dao.user.UserDaoImpl">
<propertyname="sqlTemplate"ref="sqlSessionTemplate"></property>
</bean>
<beanid="acctDao"class="com.wx.dao.account.AcountDaoImpl">
<propertyname="sqlTemplate"ref="sqlSessionTemplate"></property>
</bean>
<beanid="studentDao"class="com.wx.dao.school.StudentDaoImpl">
<propertyname="sqlTemplate"ref="sqlSessionTemplate"></property>
</bean>
<beanid="deptDao"class="com.wx.dao.school.DepartmentDaoImpl">
<propertyname="sqlTemplate"ref="sqlSessionTemplate"></property>
</bean>
</beans>
=====================================================================
步骤八:编写service层的配置文件applicationContext-service.xml,如下所示:
====================applicationContext-service.xml==================
<?xmlversion="1.0"encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<beanid="userService"class="com.wx.service.UserService">
<propertyname="userDao"ref="userDao"></property>
</bean>
<beanid="schoolService"class="com.wx.service.SchoolService">
<propertyname="deptDao"ref="deptDao"></property>
<propertyname="studentDao"ref="studentDao"></property>
</bean>
<beanid="acctService"class="com.wx.service.AccountService">
<propertyname="acctDao"ref="acctDao"></property>
</bean>
</beans>
=====================================================================
步骤九:编写spring mvc的核心配置文件springmvc-dispatcher.xml,如下所示:
==================== springmvc-dispatcher.xml==================
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEbeans PUBLIC "-//SPRING//DTDBEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 导入控制器的bean配置 -->
<importresource="classpath:configs/mvc/springmvc-controler.xml"/>
<!-- 视图解析器 -->
<beanid="resourceView"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/"></property>
<propertyname="suffix"value=".jsp"></property>
</bean>
<!-- 映射处理器 -->
<beanid="simpleUrlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="/Login.php">userControl</prop>
<propkey="/Quit.php">userControl</prop>
<propkey="/Trans.php">acctControl</prop>
<propkey="/GetAllDept.php">deptControl</prop>
<propkey="/QueryStu.php">studentControl</prop>
<propkey="/Register.php">userControl</prop>
<propkey="/ShowOneUser.php">userControl</prop>
<propkey="/CheckUser.php">userControl</prop>
</props>
</property>
</bean>
<!-- 方法名称解析器 -->
<beanid="springMethodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<propertyname="mappings">
<props>
<propkey="/Login.php">login</prop>
<propkey="/Quit.php">quit</prop>
<propkey="/Trans.php">doTransfer</prop>
<propkey="/GetAllDept.php">getAllDeptNames</prop>
<propkey="/QueryStu.php">queryAllStu</prop>
<propkey="/Register.php">register</prop>
<propkey="/ShowOneUser.php">showOne</prop>
<propkey="/CheckUser.php">isUserExist</prop>
</props>
</property>
</bean>
</beans>
=====================================================================
步骤十:编写控制器的配置文件springmvc-controler.xml,如下所示:
==================== springmvc-controler.xml==============================
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEbeans PUBLIC "-//SPRING//DTDBEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<beanid="userControl"class="com.wx.controler.user.UserControl">
<propertyname="methodNameResolver"ref="springMethodNameResolver">
</property>
<propertyname="userServ"ref="userService"></property>
</bean>
<beanid="acctControl"class="com.wx.controler.account.AccountControl">
<propertyname="methodNameResolver"ref="springMethodNameResolver">
</property>
<propertyname="acctServ"ref="acctService"></property>
</bean>
<beanid="deptControl"class="com.wx.controler.school.DepartControl">
<propertyname="methodNameResolver"ref="springMethodNameResolver">
</property>
<propertyname="schoolServ"ref="schoolService"></property>
</bean>
<beanid="studentControl"class="com.wx.controler.school.StudentControl">
<propertyname="methodNameResolver"ref="springMethodNameResolver">
</property>
<propertyname="schoolServ"ref="schoolService"></property>
</bean>
</beans>
=====================================================================
说明:其它的java类和jsp代码不一一列出,因为实在太多了,有需要请联系我。
步骤十一: 启动tomcat,发布项目,在地址栏分别输入 http://localhost:8080/SMMvc
进行测试。 登录后的结果如图所示:
联系作者: