Mybatis使用之SpringMVC整合
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Mybatis使用之SpringMVC整合
一:简介
主要记录Mybatis如何与SpringMVC框架整合。
Mybatis真正与Spring结合更能体现出其灵活、便捷的特点。
数据源交由Spring 管理、事务交由Spring管理、配置文件、映射文件交由Spring加载、初始化。
映射接口交由Spring注入等等。
大大简化了Mybatis代码、配置量。
Mybatis只需关心与数据库打交道、处理数据与实体类之间的映射即可。
二:环境介绍
主要是Mybatis3.2.8与Spring4.1.0之间的整合。
项目是使用Maven搭建的项目。
搭建步骤:
2.1 创建Maven项目
2.2 加入Mybatis+SpringMVC所需jar包依赖
2.3 配置Mybatis配置文件
2.4 配置Spring配置文件
2.5 配置SpringMVC配置文件
2.6 配置web.xml文件
2.7 配置Mybatis映射文件
2.8 编写与Mybatis映射文件对应的映射接口
2.9 配置日志资源文件
2.10 完成其他java代码编写、测试
三:具体步骤及说明
3.1 创建Maven项目
这里使用的IntellijIDEA 14、集成Maven插件、其他的IDE如Eclipse只需安装一下插件就行。
3.2 加入Mybatis+SpringMVC所需jar包依赖
具体如下面pom.xml文件所列:
<?xml version="1.0" encoding="UTF-
8"?><project xmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchem
a-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-
4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>or
g.star.coding.passion</groupId><artifactId>star-coding-passion</artifactId><version>1.0-
SNAPSHOT</version><packaging>war</packaging><properti es><java-version>1.7</java-version><org.springframework-version>4.1.0.RELEASE</org.springframework-
version><org.springframework.security-
version>3.2.0.RELEASE</org.springframework.security-version><org.aspectj-version>1.8.1</org.aspectj-
version><org.slf4j-version>1.6.1</org.slf4j-
version><org.mybatis>3.2.8</org.mybatis><org.mybatis.spring >1.2.2</org.mybatis.spring><org.aspectj>1.7.4</org.aspectj>< common.dbcp>1.4</common.dbcp><mysql.version>5.1.34</ mysql.version></properties><dependencies><!-- Spring --><dependency><groupId>org.springframework</groupId>< artifactId>spring-
core</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
web</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
oxm</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
tx</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
jdbc</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
webmvc</artifactId><version>${org.springframework-version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
aop</artifactId><version>${org.springframework-
version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-context-support</artifactId><version>${org.springframework-version}</version></dependency><dependency><groupId>or g.springframework</groupId><artifactId>spring-
test</artifactId><version>${org.springframework-
version}</version></dependency><!--aspectJ-
-><dependency><groupId>org.aspectj</groupId><artifactId> aspectjweaver</artifactId><version>1.8.5</version></depend ency><!-- Mybatis-
-><dependency><groupId>org.mybatis</groupId><artifactId >mybatis</artifactId><version>${org.mybatis}</version></de pendency><!--Mybatis Spring-
-><dependency><groupId>org.mybatis</groupId><artifactId >mybatis-
spring</artifactId><version>${org.mybatis.spring}</version>< /dependency><!--mysql-
-><dependency><groupId>mysql</groupId><artifactId>mys ql-connector-
java</artifactId><version>${mysql.version}</version></depen dency><!-- 连接池 --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-
dbcp</artifactId><version>${common.dbcp}</version></depe ndency><!-- Logging -
-><dependency><groupId>org.slf4j</groupId><artifactId>slf 4j-api</artifactId><version>${org.slf4j-
version}</version></dependency><dependency><groupId>or g.slf4j</groupId><artifactId>jcl-over-
slf4j</artifactId><version>${org.slf4j-
version}</version><scope>runtime</scope></dependency>< dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${org.slf4j-
version}</version><scope>runtime</scope></dependency>< !-- Servlet -
-><dependency><groupId>org.apache.tomcat</groupId><art ifactId>tomcat-servlet-
api</artifactId><version>7.0.30</version><scope>provided</ scope></dependency><dependency><groupId>javax.servlet.j sp</groupId><artifactId>jsp-
api</artifactId><version>2.1</version><scope>provided</sco pe></dependency><dependency><groupId>javax.servlet.jsp.j stl</groupId><artifactId>jstl-
api</artifactId><version>1.2</version><exclusions><exclusio n><groupId>javax.servlet</groupId><artifactId>servlet-
api</artifactId></exclusion></exclusions></dependency><!-- Jackson JSON Processor -
-><dependency><groupId>com.fasterxml.jackson.core</grou pId><artifactId>jackson-
databind</artifactId><version>2.4.1</version></dependency ><!-- File Upload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-
fileupload</artifactId><version>1.2.2</version></dependency ><dependency><groupId>commons-
io</groupId><artifactId>commons-
io</artifactId><version>2.0.1</version></dependency></dep endencies></project>
3.3 配置Mybatis配置文件
位于Maven的资源文件目录下:resources/mybatis/mybatis-conf ig.xml
<?xml version="1.0" encoding="UTF-
8" ?><!DOCTYPE configurationPUBLIC "-
////DTD Config 3.0//EN""/dtd/mybatis-3-
config.dtd"><configuration><!-- 命名空间 --><typeAliases><package name="org.star.coding.passion.web. model"/></typeAliases><plugins><!--分页插件、只拦截映射文件中sql语句id以ByPage结尾的sql语句、仅支持mysql和Oracle 分页--><plugin interceptor="org.star.coding.passion.web.interceptor. PageInterceptor"><property name="dialect" value="mysql"/>< /plugin></plugins><!-- 映射map --><mappers/></configuration>
3.4 配置Spring配置文件
主要是Spring与Mybatis集成、以及Spring事务以及连接池的配置、同时使用扫描加载除Controller注解标识的bean <?xml version="1.0" encoding="UTF-
8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSch ema-
instance"xmlns:context="/schema/context" xmlns:p="/schema/ p"xmlns:tx="/schema/tx" xmlns:aop="/schema/aop"xsi:schemaL ocation="/schema/beans/schema/beans/spring-
beans.xsd/schema/context/schema/context/spring-context.xsd/schema/tx /schema/tx/spring-
tx.xsd/schema/aop /schema/aop/spring-aop.xsd"><!-- 引入资源文件--><context:property-placeholder location="classpath:properties/jdbc-
config.properties"/><context:component-scan base-package="org.star.coding.passion"><context:exclude-
filter type="annotation" expression="org.springframework.stere otype.Controller"/></context:component-scan><!-
- common dbcp 数据库连接池配置信息--><bean id="dataSource" class="mons.dbcp.Ba sicDataSource" p:url="${jdbc.url}"p:driverClassName="${jdbc.dr iverClassName}" p:username="${ername}" p:password=" ${jdbc.password}"p:minEvictableIdleTimeMillis="${jdbc.minEvict ableIdleTimeMillis}" p:removeAbandoned="${jdbc.removeAban doned}"p:maxActive="${jdbc.maxActive}" p:maxIdle="${jdbc.m axIdle}" p:initialSize="${jdbc.initialSize}"p:minIdle="${jdbc.minId le}" p:maxWait="${jdbc.maxWait}" p:validationQuery="${jdbc.va lidationQuery}"p:timeBetweenEvictionRunsMillis="${jdbc.timeB etweenEvictionRunsMillis}" p:testOnBorrow="${jdbc.testOnBorr ow}"p:testOnReturn="${jdbc.testOnReturn}" p:testWhileIdle="${ jdbc.testWhileIdle}"p:removeAbandonedTimeout="${jdbc.remo veAbandonedTimeout}"/><!-- spring与mybatis整合读取所有mybatis配置文件--><bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSe ssionFactoryBean"p:dataSource-
ref="dataSource"p:configLocation="classpath:mybatis/mybatis-config.xml"p:mapperLocations="classpath:mybatis/mapper/*.x ml"/><!-- configLocation为mybatis属性 mapperLocations为所有mapper--><!-- spring与mybatis整合配置,扫描所有mapper 下mybatis配置文件、用动态代理模式来获取所有mybatis的xml文件中namespace指向的接口的代理实例。
-
-><bean class="org.mybatis.spring.mapper.MapperScannerCon figurer"p:basePackage="org.star.coding.passion.web.mapper"p:s qlSessionFactoryBeanName="sqlSessionFactory"/><!-- 对数据源进行事务管理--><bean id="transactionManager"class="org.springframework.j dbc.datasource.DataSourceTransactionManager"p:dataSource-ref="dataSource"/><!-- 事物切面配置--><tx:advice id="advice" transaction-
manager="transactionManager"><tx:attributes><tx:method na me="add*" propagation="REQUIRED" read-
only="false"/><tx:method name="save*" propagation="REQUI RED" read-
only="false"/><tx:method name="del*" propagation="REQUIRE D" read-
only="false"/><tx:method name="remove*" propagation="REQ UIRED" read-
only="false"/><tx:method name="get*" propagation="REQUIR ED" read-
only="true"/><tx:method name="query*" propagation="REQUI RED" read-
only="true"/><tx:method name="sel*" propagation="REQUIRE D" read-
only="true"/><tx:method name="mod*" propagation="REQUIR ED" read-
only="false"/><tx:method name="update*" propagation="REQ UIRED" read-
only="false"/></tx:attributes></tx:advice><tx:annotation-driven transaction-
manager="transactionManager" /><aop:config><aop:pointcut id="servicePoint" expression="execution (* org.star.coding.passi
on.web.service..*.*(..))"/><aop:advisor advice-
ref="advice" pointcut-
ref="servicePoint"/></aop:config></beans>
3.5 配置SpringMVC配置文件
SpringMVC配置信息、仅扫描Controller注解标注的类
<?xml version="1.0" encoding="UTF-
8"?><beans xmlns="/schema/beans"xmlns:p="/schema/p"xmln s:xsi="/2001/XMLSchema-
instance"xmlns:context="/schema/context"xmlns:mvc="/schem a/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spri ng-beans-3.2.xsd/schema/context/schema/context/spring-context-3.2.xsd/schema/mvc/schema/mvc/spring-mvc-
3.2.xsd"><!-- 扫描controller类--><context:component-scan base-
package="org.star.coding.passion.web.controller"/><!-- 允许静态资源访问--><mvc:annotation-driven /><mvc:default-servlet-handler/><!-- 避免IE在ajax请求时,返回json出现下载--><bean id="jacksonMessageConverter"class="org.springframe work.http.converter.json.MappingJackson2HttpMessageConvert er"><property name="supportedMediaTypes"><list><value>t ext/html;charset=UTF-
8</value></list></property></bean><!-- 对模型视图添加前后缀 --><bean id="viewResolver" class="org.springframework.web.se rvlet.view.InternalResourceViewResolver"p:prefix="/WEB-
INF/views/" p:suffix=".jsp"/><!-- 上传文件配置、多了个多请求的处理、目的是为了支持多文件上传--><bean id="multipartResolver" class="org.springframework.w monsMultipartResolver"p:defaultEn
coding="utf-
8" p:maxUploadSize="10485760000" p:maxInMemorySize="409 60"/></beans>
3.6 配置web.xml文件
配置常用信息
<web-
app xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/w eb-app_3_0.xsd"version="3.0"><!-- web root --><context-param><param-name>webAppRootKey</param-
name><param-value>springmvc.root</param-
value></context-param><!-- Spring configuration--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/spring-root-context.xml</param-value></context-param><!-
- log properties --><context-param><param-
name>log4jConfigLocation</param-name><param-
value>classpath:properties/log4j.properties</param-
value></context-param><context-param><param-
name>log4jRefreshInterval</param-name><param-
value>6000</param-value></context-
param><listener><listener-
class>org.springframework.web.util.Log4jConfigListener</listen er-class></listener><listener><listener-
class>org.springframework.web.context.ContextLoaderListener </listener-class></listener><!--Spring MVC DispatcherServlet--><servlet><servlet-name>appServlet</servlet-
name><servlet-
class>org.springframework.web.servlet.DispatcherServlet</servl
et-class><init-param><param-
name>contextConfigLocation</param-name><param-value>classpath:spring/springMVC-root-context.xml</param-value></init-param><load-on-startup>2</load-on-startup><!--<async-supported>true</async-supported>--></servlet><servlet-mapping><servlet-
name>appServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- Spring encoding filter -
-><filter><filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name><url-
pattern>/*</url-pattern></filter-mapping><!-
- error handle page --><error-page><!-- wrong path -
-><error-code>404</error-code><location>/WEB-
INF/views/error/404.jsp</location></error-page><error-page><!-- no privilege --><error-code>405</error-
code><location>/WEB-
INF/views/error/405.jsp</location></error-page><error-page><!-- internal error --><error-code>500</error-
code><location>/WEB-
INF/views/error/500.jsp</location></error-page><error-page><!--internal exception--><exception-
type>ng.Exception</exception-type><location>/WEB-INF/views/error/400.jsp</location></error-page><!--
welcome page list--><welcome-file-list><welcome-
file>index.jsp</welcome-file><welcome-
file>welcome.jsp</welcome-file></welcome-file-list></web-app>
3.7 配置Mybatis映射文件
<?xml version="1.0" encoding="UTF-
8" ?><!DOCTYPE mapper PUBLIC "-
////DTD Mapper 3.0//EN" "/dtd/mybatis-3-
mapper.dtd"><mapper namespace="org.star.coding.passion.we erMapper"><select id="selectUserCount" resultTyp e="int">SELECT count(1)FROM klmy_person</select></mapper>
3.8 编写与Mybatis映射文件对应的映射接口
package org.star.coding.passion.web.mapper;/*** Created b
y andy on 5/9/2015.<br>* Version 1.0-
SNAPSHOT<br>*/public interface UserMapper {int selectUserC ount();}
3.9 配置日志资源文件
### set log levels ###log4j.rootLogger = info , stdout , D , E ### output to the console ###log4j.appender.stdout = org.apa che.log4j.ConsoleAppenderlog4j.appender.stdout.Target = Syste yout = org.apache.log4j.PatternLa yout.ConversionPattern = %d{yyyy-MM-
dd HH:mm:ss} [%c:%L] [%p] - %m%n### output mybatis sql inf
o to the console ###.star.coding.passion=DEBU
G#.mybatis=DEBUG#.apache=D EBUG#log4j.logger.java.sql.Connection=DEBUG#log4j.logger.jav
a.sql.Statement=DEBUG#log4j.logger.java.sql.PreparedStatemen t=DEBUG### Output to the log file ###log4j.appender.D = org. apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = ${ springmvc.root}/WEB-
INF/logs/log.loglog4j.appender.D.Append = truelog4j.appender.
D.Threshold = yout = org.apache.log4j yout.ConversionPattern = %d{ yyyy-MM-
dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n### Save exception inf ormation to separate file ###log4j.appender.E = org.apache.log
4j.DailyRollingFileAppenderlog4j.appender.E.File = ${springmvc. root}/WEB-
INF/logs/error.loglog4j.appender.E.Append = truelog4j.appende r.E.Threshold = yout = org.apache.log4j. yout.ConversionPattern = %d{y yyy-MM-dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n
四:补充
需要注意Spring的配置文件与SpringMVC的配置文件是分开的、两者分配在初始化Spring容器的时候扫描加载的bean不同、Spring 是扫描加载除Controller注解以外符合加载条件的bean、而SpringMVC是只扫描加载Controller注解的bean、目的是为了在加载Controller时注入的Service是具有事务特性的bean。
如果项目中事务不起作用、请查看是否是此原因导致。
项目下载地址:/detail/chenghuaying/8761971。