企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.star.coding.passion</groupId> <artifactId>star-coding-passion</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <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>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.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> </dependency> <!-- Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${org.mybatis}</version> </dependency> <!--Mybatis Spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${org.mybatis.spring}</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 连接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>${common.dbcp}</version> </dependency> <!-- Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${org.slf4j-version}</version> </dependency> <dependency> <groupId>org.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> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.30</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> </exclusions> </dependency> <!-- Jackson JSON Processor --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <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> </dependencies> </project> ~~~ ###           3.3 配置Mybatis配置文件         位于Maven的资源文件目录下: resources/mybatis/mybatis-config.xml ~~~ <?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> <!-- 命名空间 --> <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="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/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.stereotype.Controller"/> </context:component-scan> <!-- common dbcp 数据库连接池配置信息--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" p:url="${jdbc.url}" p:driverClassName="${jdbc.driverClassName}" p:username="${jdbc.username}" p:password="${jdbc.password}" p:minEvictableIdleTimeMillis="${jdbc.minEvictableIdleTimeMillis}" p:removeAbandoned="${jdbc.removeAbandoned}" p:maxActive="${jdbc.maxActive}" p:maxIdle="${jdbc.maxIdle}" p:initialSize="${jdbc.initialSize}" p:minIdle="${jdbc.minIdle}" p:maxWait="${jdbc.maxWait}" p:validationQuery="${jdbc.validationQuery}" p:timeBetweenEvictionRunsMillis="${jdbc.timeBetweenEvictionRunsMillis}" p:testOnBorrow="${jdbc.testOnBorrow}" p:testOnReturn="${jdbc.testOnReturn}" p:testWhileIdle="${jdbc.testWhileIdle}" p:removeAbandonedTimeout="${jdbc.removeAbandonedTimeout}"/> <!-- spring与mybatis整合 读取所有mybatis配置文件--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis/mybatis-config.xml" p:mapperLocations="classpath:mybatis/mapper/*.xml"/> <!-- configLocation为mybatis属性 mapperLocations为所有mapper--> <!-- spring与mybatis整合配置,扫描所有mapper下mybatis配置文件、用动态代理模式来获取所有mybatis的xml文件中namespace指 向的接口的代理实例。--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="org.star.coding.passion.web.mapper" p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- 对数据源进行事务管理--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <!-- 事物切面配置--> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" read-only="false"/> <tx:method name="save*" propagation="REQUIRED" read-only="false"/> <tx:method name="del*" propagation="REQUIRED" read-only="false"/> <tx:method name="remove*" propagation="REQUIRED" read-only="false"/> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="query*" propagation="REQUIRED" read-only="true"/> <tx:method name="sel*" propagation="REQUIRED" read-only="true"/> <tx:method name="mod*" propagation="REQUIRED" read-only="false"/> <tx:method name="update*" propagation="REQUIRED" read-only="false"/> </tx:attributes> </tx:advice> <tx:annotation-driven transaction-manager="transactionManager" /> <aop:config> <aop:pointcut id="servicePoint" expression="execution (* org.star.coding.passion.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="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/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.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 对模型视图添加前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp"/> <!-- 上传文件配置 、多了个多请求的处理、目的是为了支持多文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" p:maxUploadSize="10485760000" p:maxInMemorySize="40960"/> </beans> ~~~ ###           3.6 配置web.xml文件        配置常用信息 ~~~ <web-app 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_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</listener-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</servlet-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>java.lang.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 "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.star.coding.passion.web.mapper.UserMapper"> <select id="selectUserCount" resultType="int"> SELECT count(1) FROM klmy_person </select> </mapper> ~~~ ###           3.8 编写与Mybatis映射文件对应的映射接口 ~~~ package org.star.coding.passion.web.mapper; /** * Created by andy on 5/9/2015.<br> * Version 1.0-SNAPSHOT<br> */ public interface UserMapper { int selectUserCount(); } ~~~ ###           3.9 配置日志资源文件 ~~~ ### set log levels ### log4j.rootLogger = info , stdout , D , E ### output to the console ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%c:%L] [%p] - %m%n ### output mybatis sql info to the console ### log4j.logger.org.star.coding.passion=DEBUG #log4j.logger.org.mybatis=DEBUG #log4j.logger.org.apache=DEBUG #log4j.logger.java.sql.Connection=DEBUG #log4j.logger.java.sql.Statement=DEBUG #log4j.logger.java.sql.PreparedStatement=DEBUG ### Output to the log file ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = debug log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n ### Save exception information to separate file ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = ${springmvc.root}/WEB-INF/logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = warn log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} [%t] [%c:%L] [%p] - %m%n ~~~ ### 四:补充        需要注意Spring的配置文件与SpringMVC的配置文件是分开的、两者分配在初始化Spring容器的时候扫描加载的bean不同、Spring是扫描加载除Controller注解以外符合加载条件的bean、而SpringMVC是只扫描加载Controller注解的bean、目的是为了在加载Controller时注入的Service是具有事务特性的bean。如果项目中事务不起作用、请查看是否是此原因导致。       更多内容:[Mybatis 目录](http://blog.csdn.net/crave_shy/article/details/45825599)        项目下载地址:http://download.csdn.net/detail/chenghuaying/8761971