本文示例在如下环境下搭建一个Maven+Druid+SSM+PageHelper以及Mybatis Generator反向生成代码的项目
一.开发环境:
系统:Windows7-旗舰版
工具:Eclipse MARS,Navicat Premium 12
JDK:1.8.0_121
Tomcat:8.0.43
MySQL :5.6.5-m8
二.搭建流程:
一.环境准备
1.1 配置JDK
在window--》Preferences下搜索Java,选择本地对应的JDK安装目录,点击添加完成:
配置完开发环境JDK后,需要修改项目默认的编译环境:
1.2 配置Tomcat
在window--》Preferences下搜索Server,选择自己本地对应的Tomcat版本及JRE环境,点击添加完成:
添加完成之后,配置Tomcat,如图所示,分别对应项目发布路径、自动部署、发布超时时间、访问端口等配置
1.3 配置Maven
在window--》Preferences下搜索Maven,选择本地Maven安装路径:
添加Maven后配置自定义属性,替换自己的Maven settings配置文件及Maven仓库:
二.创建项目
2.1 使用Eclipse创建Maven项目:
2.2 项目创建完成后,根据自己习惯的包名结构创建对应的目录,项目结构如图所示:
三.配置pom.xml依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 <groupId>com</groupId> 6 <artifactId>mySpringMVC</artifactId> 7 <packaging>war</packaging> 8 <version>0.0.1-SNAPSHOT</version> 9 <name>mySpringMVC Maven Webapp</name> 10 <url>http://maven.apache.org</url> 11 12 <properties> 13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 14 15 <jdk.version>1.8</jdk.version> 16 <spring.version>4.1.9.RELEASE</spring.version> 17 <mysql-connector>8.0.13</mysql-connector> 18 <druid.version>1.0.18</druid.version> 19 <mybatis.version>3.2.8</mybatis.version> 20 <mybatis-spring.version>1.2.3</mybatis-spring.version> 21 <mybatis-generator.version>1.3.5</mybatis-generator.version> 22 </properties> 23 24 <!-- 定义Maven项目依赖 --> 25 <dependencies> 26 <!-- Junit 测试依赖 --> 27 <dependency> 28 <groupId>junit</groupId> 29 <artifactId>junit</artifactId> 30 <version>3.8.1</version> 31 <!-- 表示开发的时候引入,发布的时候不会加载此包 --> 32 <scope>test</scope> 33 </dependency> 34 35 <!-- spring核心依赖 --> 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-core</artifactId> 39 <version>${spring.version}</version> 40 </dependency> 41 42 <!-- springWeb依赖 --> 43 <dependency> 44 <groupId>org.springframework</groupId> 45 <artifactId>spring-web</artifactId> 46 <version>${spring.version}</version> 47 </dependency> 48 49 <!-- springMVC依赖 --> 50 <dependency> 51 <groupId>org.springframework</groupId> 52 <artifactId>spring-webmvc</artifactId> 53 <version>${spring.version}</version> 54 </dependency> 55 56 <!-- springJDBC依赖 --> 57 <dependency> 58 <groupId>org.springframework</groupId> 59 <artifactId>spring-jdbc</artifactId> 60 <version>${spring.version}</version> 61 </dependency> 62 63 <!-- spring上下文依赖 --> 64 <dependency> 65 <groupId>org.springframework</groupId> 66 <artifactId>spring-context</artifactId> 67 <version>${spring.version}</version> 68 </dependency> 69 70 <!-- spring上下文支持依赖 --> 71 <dependency> 72 <groupId>org.springframework</groupId> 73 <artifactId>spring-context-support</artifactId> 74 <version>${spring.version}</version> 75 </dependency> 76 77 <!-- springAOP依赖 --> 78 <dependency> 79 <groupId>org.springframework</groupId> 80 <artifactId>spring-aop</artifactId> 81 <version>${spring.version}</version> 82 </dependency> 83 84 <!-- spring测试依赖 --> 85 <dependency> 86 <groupId>org.springframework</groupId> 87 <artifactId>spring-test</artifactId> 88 <version>${spring.version}</version> 89 </dependency> 90 91 <!-- spring OXM依赖 --> 92 <dependency> 93 <groupId>org.springframework</groupId> 94 <artifactId>spring-oxm</artifactId> 95 <version>${spring.version}</version> 96 </dependency> 97 98 <!-- spring 事务依赖 --> 99 <dependency> 100 <groupId>org.springframework</groupId> 101 <artifactId>spring-tx</artifactId> 102 <version>${spring.version}</version> 103 </dependency> 104 105 <!-- Servlet依赖 --> 106 <dependency> 107 <groupId>javax.servlet</groupId> 108 <artifactId>javax.servlet-api</artifactId> 109 <version>3.0.1</version> 110 <scope>provided</scope> 111 </dependency> 112 113 <dependency> 114 <groupId>javax.servlet</groupId> 115 <artifactId>jstl</artifactId> 116 <version>1.1.2</version> 117 <scope>provided</scope> 118 </dependency> 119 120 <!-- jsp依赖 --> 121 <dependency> 122 <groupId>javax.servlet.jsp</groupId> 123 <artifactId>javax.servlet.jsp-api</artifactId> 124 <version>2.3.1</version> 125 <scope>provided</scope> 126 </dependency> 127 128 <!-- jackson 依赖 --> 129 <dependency> 130 <groupId>org.codehaus.jackson</groupId> 131 <artifactId>jackson-jaxrs</artifactId> 132 <version>1.9.11</version> 133 </dependency> 134 135 <!-- commons 依赖 --> 136 <dependency> 137 <groupId>org.apache.commons</groupId> 138 <artifactId>commons-lang3</artifactId> 139 <version>3.3.2</version> 140 </dependency> 141 142 <dependency> 143 <groupId>commons-io</groupId> 144 <artifactId>commons-io</artifactId> 145 <version>2.4</version> 146 </dependency> 147 148 <dependency> 149 <groupId>org.apache.commons</groupId> 150 <artifactId>commons-collections4</artifactId> 151 <version>4.0</version> 152 </dependency> 153 154 <dependency> 155 <groupId>commons-logging</groupId> 156 <artifactId>commons-logging</artifactId> 157 <version>1.1.3</version> 158 </dependency> 159 160 <dependency> 161 <groupId>commons-codec</groupId> 162 <artifactId>commons-codec</artifactId> 163 <version>1.8</version> 164 </dependency> 165 <dependency> 166 <groupId>commons-beanutils</groupId> 167 <artifactId>commons-beanutils</artifactId> 168 <version>1.8.3</version> 169 </dependency> 170 171 <dependency> 172 <groupId>commons-chain</groupId> 173 <artifactId>commons-chain</artifactId> 174 <version>1.2</version> 175 </dependency> 176 177 <dependency> 178 <groupId>commons-fileupload</groupId> 179 <artifactId>commons-fileupload</artifactId> 180 <version>1.3.1</version> 181 </dependency> 182 183 <dependency> 184 <groupId>org.apache.commons</groupId> 185 <artifactId>commons-math3</artifactId> 186 <version>3.3</version> 187 </dependency> 188 189 <dependency> 190 <groupId>org.apache.commons</groupId> 191 <artifactId>commons-pool2</artifactId> 192 <version>2.2</version> 193 </dependency> 194 195 <dependency> 196 <groupId>org.apache.commons</groupId> 197 <artifactId>commons-digester3</artifactId> 198 <version>3.2</version> 199 </dependency> 200 201 <dependency> 202 <groupId>commons-net</groupId> 203 <artifactId>commons-net</artifactId> 204 <version>3.3</version> 205 </dependency> 206 207 <dependency> 208 <groupId>commons-dbutils</groupId> 209 <artifactId>commons-dbutils</artifactId> 210 <version>1.5</version> 211 </dependency> 212 213 <dependency> 214 <groupId>org.apache.commons</groupId> 215 <artifactId>commons-email</artifactId> 216 <version>1.3.3</version> 217 </dependency> 218 219 <dependency> 220 <groupId>commons-dbcp</groupId> 221 <artifactId>commons-dbcp</artifactId> 222 <version>1.4</version> 223 </dependency> 224 225 <!-- jstl依赖 --> 226 <dependency> 227 <groupId>jstl</groupId> 228 <artifactId>jstl</artifactId> 229 <version>1.2</version> 230 </dependency> 231 232 <!-- 标签库依赖 --> 233 <dependency> 234 <groupId>taglibs</groupId> 235 <artifactId>standard</artifactId> 236 <version>1.1.2</version> 237 </dependency> 238 239 <!-- 日志相关 --> 240 <dependency> 241 <groupId>log4j</groupId> 242 <artifactId>log4j</artifactId> 243 <version>1.2.16</version> 244 </dependency> 245 246 <dependency> 247 <groupId>org.slf4j</groupId> 248 <artifactId>slf4j-api</artifactId> 249 <version>1.7.5</version> 250 </dependency> 251 252 <!-- 阿里连接池依赖 --> 253 <dependency> 254 <groupId>com.alibaba</groupId> 255 <artifactId>druid</artifactId> 256 <version>${druid.version}</version> 257 </dependency> 258 259 <!-- 阿里fastjson依赖 --> 260 <dependency> 261 <groupId>com.alibaba</groupId> 262 <artifactId>fastjson</artifactId> 263 <version>1.1.41</version> 264 </dependency> 265 266 <!-- 引入jackson,防止ajax调用返回json出现下载文件 --> 267 <dependency> 268 <groupId>com.fasterxml.jackson.core</groupId> 269 <artifactId>jackson-databind</artifactId> 270 <version>2.5.1</version> 271 </dependency> 272 273 <!-- mysql连接 --> 274 <dependency> 275 <groupId>mysql</groupId> 276 <artifactId>mysql-connector-java</artifactId> 277 <version>${mysql-connector}</version> 278 </dependency> 279 280 <!-- MyBatis --> 281 <dependency> 282 <groupId>org.mybatis</groupId> 283 <artifactId>mybatis</artifactId> 284 <version>${mybatis.version}</version> 285 </dependency> 286 287 <!-- MyBatis/Spring包 --> 288 <dependency> 289 <groupId>org.mybatis</groupId> 290 <artifactId>mybatis-spring</artifactId> 291 <version>${mybatis-spring.version}</version> 292 </dependency> 293 294 <!-- MyBatis Generator 反向生成 --> 295 <dependency> 296 <groupId>org.mybatis.generator</groupId> 297 <artifactId>mybatis-generator-core</artifactId> 298 <version>${mybatis-generator.version}</version> 299 </dependency> 300 301 <!-- MyBatis分页插件依赖 --> 302 <dependency> 303 <groupId>com.github.pagehelper</groupId> 304 <artifactId>pagehelper</artifactId> 305 <version>4.0.0</version> 306 </dependency> 307 </dependencies> 308 309 <build> 310 <!-- 定义配置文件的路径 --> 311 <resources> 312 <resource> 313 <directory>src/main/resources</directory> 314 <filtering>true</filtering> 315 </resource> 316 </resources> 317 318 <finalName>mySpringMVC</finalName> 319 320 <plugins> 321 <!-- 定义mybatis generator 反向生成插件 --> 322 <plugin> 323 <groupId>org.mybatis.generator</groupId> 324 <artifactId>mybatis-generator-maven-plugin</artifactId> 325 <version>1.3.2</version> 326 <executions> 327 <execution> 328 <id>Generate MyBatis Files</id> 329 <goals> 330 <goal>generate</goal> 331 </goals> 332 <phase>generate</phase> 333 <configuration> 334 <verbose>true</verbose> 335 <overwrite>true</overwrite> 336 </configuration> 337 </execution> 338 </executions> 339 340 <dependencies> 341 <dependency> 342 <groupId>mysql</groupId> 343 <artifactId>mysql-connector-java</artifactId> 344 <version>${mysql-connector}</version> 345 </dependency> 346 347 <dependency> 348 <groupId>org.mybatis.generator</groupId> 349 <artifactId>mybatis-generator-core</artifactId> 350 <version>${mybatis-generator.version}</version> 351 </dependency> 352 353 354 <dependency> 355 <groupId>org.mybatis</groupId> 356 <artifactId>mybatis</artifactId> 357 <version>${mybatis.version}</version> 358 </dependency> 359 </dependencies> 360 </plugin> 361 </plugins> 362 </build> 363 364 </project>
四.搭建框架
在如图所示目录下,分别创建
mapping:用于存放实体与数据库映射的Mybatis配置文件
application.properties:项目通用配置文件
generatorConfig.xml:Mybatis反向生成配置文件
log4j.properties:log4j日志记录配置文件
mybatis-config.xml:Mybatis配置文件
spring-mvc.xml:SpringMVC配置文件
spring-mybatis.xml:Spring整合Mybatis配置文件
4.1 项目基本配置:application.properties
#默认访问页面
web.view.default=../index
#最多文件上传大小
web.maxUploadSize=10485760000
#定义jsp页面访问路径前后缀
web.view.prefix=/WEB-INF/views/
web.view.suffix=.jsp
#JDBC配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&serverTimezone=GMT
jdbc.username=root
jdbc.password=root
jdbc.initialSize=0
jdbc.maxActive=20
jdbc.maxIdle=20
jdbc.minIdle=1
jdbc.maxWait=60000
#阿里druid连接池配置
dbcp.initialSize=15
dbcp.maxActive=5000
dbcp.maxIdle=0
dbcp.maxWait=900000
dbcp.defaultAutoCommit=true
dbcp.removeAbandoned=true
dbcp.removeAbandonedTimeout=30
dbcp.whenExhaustedAction=1
dbcp.validationQuery=select 1
dbcp.testOnBorrow=fasle
dbcp.testOnReturn=false
4.2 日志记录:log4j.properties
#定义LOG输出级别 log4j.rootLogger=INFO,Console,File #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #文件大小到达指定尺寸的时候产生一个新的文件 log4j.appender.File = org.apache.log4j.RollingFileAppender #指定输出目录 log4j.appender.File.File = logs/springmvcMybist/ssm.log #定义文件最大大小 log4j.appender.File.MaxFileSize = 10MB #输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
4.3 配置Mybatis框架及PageHelper插件:mybatis-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 <configuration> 4 5 <!-- 全局参数 --> 6 <settings> 7 <!-- 使全局的映射器启用或禁用缓存。 --> 8 <setting name="cacheEnabled" value="true"/> 9 10 <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --> 11 <setting name="lazyLoadingEnabled" value="true"/> 12 13 <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 --> 14 <setting name="aggressiveLazyLoading" value="true"/> 15 16 <!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true --> 17 <setting name="multipleResultSetsEnabled" value="true"/> 18 19 <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true --> 20 <setting name="useColumnLabel" value="true"/> 21 22 <!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false --> 23 <setting name="useGeneratedKeys" value="false"/> 24 25 <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 --> 26 <setting name="autoMappingBehavior" value="PARTIAL"/> 27 28 <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) --> 29 <setting name="defaultExecutorType" value="SIMPLE"/> 30 31 <!-- 使用驼峰命名法转换字段。 --> 32 <setting name="mapUnderscoreToCamelCase" value="true"/> 33 34 <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session --> 35 <setting name="localCacheScope" value="SESSION"/> 36 37 <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 --> 38 <setting name="jdbcTypeForNull" value="NULL"/> 39 40 <!-- 打印sql语句 --> 41 <setting name="logImpl" value="STDOUT_LOGGING" /> 42 </settings> 43 44 <!-- 定义MyBatis插件 --> 45 <plugins> 46 <plugin interceptor="com.github.pagehelper.PageHelper"> 47 <!-- 数据库类型 --> 48 <property name="dialect" value="mysql"/> 49 <!-- 该参数默认为false --> 50 <!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 --> 51 <!-- 和startPage中的pageNum效果一样--> 52 <property name="offsetAsPageNum" value="true"/> 53 <!-- 该参数默认为false --> 54 <!-- 设置为true时,使用RowBounds分页会进行count查询 --> 55 <property name="rowBoundsWithCount" value="true"/> 56 <!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 --> 57 <!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)--> 58 <property name="pageSizeZero" value="true"/> 59 <!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 --> 60 <!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 --> 61 <!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 --> 62 <property name="reasonable" value="false"/> 63 <!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 --> 64 <!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 --> 65 <!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 --> 66 <!-- 不理解该含义的前提下,不要随便复制该配置 --> 67 <property name="params" value="pageNum=start;pageSize=limit;"/> 68 <!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page --> 69 <property name="returnPageInfo" value="check"/> 70 </plugin> 71 </plugins> 72 </configuration>
4.4 整合MVC:spring-mvc.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 5 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 6 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 7 8 <description>SpringMVC配置文件</description> 9 10 <!-- 引入配置文件 --> 11 <bean id="propertyConfigurer" 12 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 13 <property name="location" value="classpath:application.properties" /> 14 </bean> 15 16 <!-- 自动扫描Controller包 --> 17 <context:component-scan base-package="com.controller" /> 18 19 <!-- 添加注解驱动 --> 20 <mvc:annotation-driven enable-matrix-variables="true" /> 21 22 <!-- 以下两种对静态资源的配置选中一种即可 --> 23 <!-- 1.允许对静态资源文件的访问 , 将无法mapping到Controller的path交给default servlet handler处理--> 24 <mvc:default-servlet-handler /> 25 26 <!-- 2.对静态资源的访问,mapping:访问路径,location:静态资源的位置 --> 27 <mvc:resources mapping="/static/**" location="/static/" /> 28 29 <!-- 定义默认的访问页面 --> 30 <mvc:view-controller path="/" view-name="${web.view.default}"/> 31 32 <!--避免IE执行AJAX时,返回JSON出现下载文件,Spring4.1.1去掉了MappingJacksonHttpMessageConverter 33 spring-mvc配置将MappingJacksonHttpMessageConverter改成MappingJackson2HttpMessageConverter, 34 Maven对org.codehaus.jackson的引用,改用 com.fasterxml.jackson.core --> 35 <bean id="mappingJacksonHttpMessageConverter" 36 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 37 <property name="supportedMediaTypes"> 38 <list> 39 <value>text/html;charset=UTF-8</value> 40 </list> 41 </property> 42 </bean> 43 44 <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> 45 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 46 <property name="messageConverters"> 47 <list> 48 <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> 49 </list> 50 </property> 51 </bean> 52 53 <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> 54 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 55 <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> 56 <property name="prefix" value="${web.view.prefix}" /> 57 <property name="suffix" value="${web.view.suffix}" /> 58 </bean> 59 60 <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> 61 <bean id="multipartResolver" 62 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 63 <!-- 默认编码 --> 64 <property name="defaultEncoding" value="UTF-8" /> 65 <!-- 文件大小最大值 --> 66 <property name="maxUploadSize" value="${web.maxUploadSize}" /> 67 <!-- 内存中的最大值 --> 68 <property name="maxInMemorySize" value="40960" /> 69 </bean> 70 </beans>
4.5 整合Mybatis: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" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" 5 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 6 xmlns:task="http://www.springframework.org/schema/task" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 9 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 10 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd 11 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd 12 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 13 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd 14 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd" 15 default-lazy-init="true"> 16 17 <description>Spring整合Mybatis配置文件</description> 18 19 <!-- 引入配置文件 --> 20 <bean id="propertyConfigurer" 21 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 22 <property name="location" value="classpath:application.properties" /> 23 </bean> 24 25 <!-- 自动扫描 --> 26 <context:component-scan base-package="com.dao,com.service" /> 27 28 <!-- 阿里 druid 数据库连接池 --> 29 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 30 destroy-method="close"> 31 <property name="driverClassName" value="${jdbc.driver}" /> 32 <property name="url" value="${jdbc.url}" /> 33 <property name="username" value="${jdbc.username}" /> 34 <property name="password" value="${jdbc.password}" /> 35 <!-- 初始化连接数量 --> 36 <property name="initialSize" value="${jdbc.initialSize}"></property> 37 <!-- 最大并发连接数 --> 38 <property name="maxActive" value="${jdbc.maxActive}"></property> 39 <!-- 最大空闲连接数 --> 40 <property name="maxIdle" value="${jdbc.maxIdle}"></property> 41 <!-- 最小空闲连接数 --> 42 <property name="minIdle" value="${jdbc.minIdle}"></property> 43 <!-- 配置获取连接等待超时的时间 --> 44 <property name="maxWait" value="${jdbc.maxWait}"></property> 45 <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" /> 46 <property name="removeAbandoned" value="${dbcp.removeAbandoned}" /> 47 <property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}" /> 48 <property name="logAbandoned" value="true"></property> 49 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> 50 <property name="timeBetweenEvictionRunsMillis" value="60000" /> 51 52 <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> 53 <property name="minEvictableIdleTimeMillis" value="300000" /> 54 <property name="validationQuery" value="${dbcp.validationQuery}" /> 55 <property name="testWhileIdle" value="true" /> 56 <property name="testOnBorrow" value="false" /> 57 <property name="testOnReturn" value="false" /> 58 59 <!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false。--> 60 <property name="poolPreparedStatements" value="false" /> 61 <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> 62 63 <!-- 配置监控统计拦截的filters --> 64 <property name="filters" value="stat" /> 65 </bean> 66 67 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> 68 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 69 <property name="dataSource" ref="dataSource" /> 70 <!-- 自动扫描mapping.xml文件 --> 71 <property name="mapperLocations" value="classpath:/mapping/*.xml"></property> 72 <property name="configLocation" value="classpath:/mybatis-config.xml"></property> 73 </bean> 74 75 <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 76 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 77 <property name="basePackage" value="com.dao" /> 78 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 79 </bean> 80 81 <!-- 事务管理--> 82 <bean id="transactionManager" 83 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 84 <property name="dataSource" ref="dataSource" /> 85 </bean> 86 87 <!-- 可通过注解控制事务 --> 88 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> 89 90 </beans>
4.6 配置反向生成:generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动,请按实际填写本地的mysql连接jar包路径 --> <classPathEntry location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.31\mysql-connector-java-5.1.31.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/wh-spring-boot" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="com.entity" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名, domainObjectName是实体类名 --> <table tableName="sys_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <table tableName="sys_role" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <table tableName="sys_menu" domainObjectName="Menu" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> <table tableName="r_user_role" domainObjectName="UserRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
配置完成反向生成文件后,配置如下图所示Run Configurations,右键Run as Configurations 即可在对应的包下面反向生成代码:
默认生成的Dao层格式为:XXXMapper,这里根据个人习惯可另外自行修改名称:
4.7 配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 version="3.0"> 6 <display-name>Archetype Created Web Application</display-name> 7 8 <!-- Spring和Mybatis整合的的配置文件 --> 9 <context-param> 10 <param-name>contextConfigLocation</param-name> 11 <param-value>classpath:spring-mybatis.xml</param-value> 12 </context-param> 13 14 <!-- 编码过滤器 --> 15 <filter> 16 <filter-name>encodingFilter</filter-name> 17 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 18 <async-supported>true</async-supported> 19 <init-param> 20 <param-name>encoding</param-name> 21 <param-value>UTF-8</param-value> 22 </init-param> 23 </filter> 24 <filter-mapping> 25 <filter-name>encodingFilter</filter-name> 26 <url-pattern>/*</url-pattern> 27 </filter-mapping> 28 29 <!-- Spring监听器 --> 30 <listener> 31 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 32 </listener> 33 34 <!-- 防止Spring内存溢出监听器 --> 35 <listener> 36 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 37 </listener> 38 39 <!-- Spring MVC 核心:DispatcherServlet --> 40 <servlet> 41 <servlet-name>SpringMVC</servlet-name> 42 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 43 <init-param> 44 <param-name>contextConfigLocation</param-name> 45 <param-value>classpath:spring-mvc.xml</param-value> 46 </init-param> 47 <load-on-startup>1</load-on-startup> 48 <async-supported>true</async-supported> 49 </servlet> 50 51 <servlet-mapping> 52 <servlet-name>SpringMVC</servlet-name> 53 <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> 54 <url-pattern>/</url-pattern> 55 </servlet-mapping> 56 57 <!--阿里druid连接池启用Web监控统计功能start --> 58 <filter> 59 <filter-name>DruidWebStatFilter</filter-name> 60 <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> 61 <init-param> 62 <param-name>exclusions</param-name> 63 <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> 64 </init-param> 65 </filter> 66 <filter-mapping> 67 <filter-name>DruidWebStatFilter</filter-name> 68 <url-pattern>/*</url-pattern> 69 </filter-mapping> 70 71 <servlet> 72 <servlet-name>DruidStatView</servlet-name> 73 <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> 74 </servlet> 75 <servlet-mapping> 76 <servlet-name>DruidStatView</servlet-name> 77 <url-pattern>/druid/*</url-pattern> 78 </servlet-mapping> 79 <!--连接池启用Web监控统计功能end--> 80 81 82 <welcome-file-list> 83 <welcome-file>/WEB-INF/index.jsp</welcome-file> 84 </welcome-file-list> 85 </web-app>
五.测试准备
5.1 Web访问测试
在Controller包下新建TestController,此Controller只有一个helloWorld方法用于向页面返回文字:
1 package com.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 /** 8 * 测试Controller 9 * @author ljh 10 */ 11 @Controller 12 public class TestController { 13 14 /** 15 * 测试访问 16 * @return 17 */ 18 @RequestMapping("/helloWorld") 19 @ResponseBody 20 public String helloWorld(){ 21 return "HelloWorld"; 22 } 23 }
5.2 持久层数据库连接测试
5.2.1 创建Service
在service包下创建UserService接口,与UserServiceImpl接口实现:
1 package com.service; 2 3 import java.util.List; 4 5 import com.entity.User; 6 import com.github.pagehelper.PageInfo; 7 8 /** 9 * User service层接口 10 * @author ljh 11 */ 12 public interface UserService { 13 int deleteByID(Integer id); 14 15 int insert(User user); 16 17 User selectByID(Integer id); 18 19 int update(User record); 20 21 List<User> selectUserList(User user); 22 23 /** 24 * 分页查询用户列表 25 * @param user 过滤条件 26 * @param pageNo 页码 27 * @param pageSize 页宽 28 * @return 29 */ 30 PageInfo<User> selectUserByPage(User user,int pageNo,int pageSize); 31 }
1 package com.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 8 import com.dao.UserDao; 9 import com.entity.User; 10 import com.github.pagehelper.PageHelper; 11 import com.github.pagehelper.PageInfo; 12 import com.service.UserService; 13 14 /** 15 * User service层接口实现 16 * @author ljh 17 */ 18 @Service 19 public class UserServiceImpl implements UserService{ 20 @Autowired 21 private UserDao userDao; 22 23 @Override 24 public int deleteByID(Integer id) { 25 return userDao.deleteByID(id); 26 } 27 28 @Override 29 public int insert(User record) { 30 return userDao.insert(record); 31 } 32 33 @Override 34 public User selectByID(Integer id) { 35 return userDao.selectByID(id); 36 } 37 38 @Override 39 public int update(User record) { 40 return userDao.update(record); 41 } 42 43 @Override 44 public List<User> selectUserList(User user) { 45 return userDao.selectUserList(user); 46 } 47 48 /** 49 * 分页查询用户列表 50 * @param user 过滤条件 51 * @param pageNo 页码 52 * @param pageSize 页宽 53 * @return 54 */ 55 @Override 56 public PageInfo<User> selectUserByPage(User user, int pageNo, int pageSize) { 57 PageHelper.startPage(pageNo, pageSize); 58 List<User> list = userDao.selectUserList(user); 59 //用PageInfo对结果进行包装 60 PageInfo<User> pageInfo = new PageInfo<User>(list); 61 return pageInfo; 62 } 63 64 }
5.2.2 创建Junit单元测试
在test包下创建TestUserService,并添加Junit测试相关注解:
1 package test; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.test.context.ContextConfiguration; 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 import com.entity.User; 9 import com.github.pagehelper.PageInfo; 10 import com.service.UserService; 11 12 @RunWith(SpringJUnit4ClassRunner.class) 13 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml","classpath:spring-mvc.xml"}) 14 public class TestUserService { 15 16 @Autowired 17 private UserService userService; 18 19 @Test 20 public void test(){ 21 PageInfo<User> userPageInfo = userService.selectUserByPage(new User(), 1, 10); 22 for (User user : userPageInfo.getList()) { 23 System.out.println(user.getName()); 24 } 25 } 26 }
六.运行与测试
6.1 将项目添加进Tomcat应用服务器,并启动Tomcat:
6.2 测试Web访问
打开浏览器在地址栏输入http://localhost:8080/mySpringMVC/helloWorld查看运行结果:
6.3 测试持久层数据库连接
在TestUserService类中右键运行Junit测试方法:
原文地址:https://www.cnblogs.com/ljhblogs/p/11039255.html