SSM 最简单最全面的整合Spring+SpringMVC+Mybatis三大框架 快速搭建
前文啰嗦:
之前一直使用SpringBoot ,有好一段时间没去一步步整合SSM框架去做项目了,最近有小伙伴在我其他博客的留言,让我感觉到初学者虽然简单学会SpringBoot,确实能快速上手开发项目,但是可能会因为SpringBoot省掉了很多配置导致自己从来没见过SSM里面都有些什么配置,这样其实是比较不好的。 所以,我决定写一篇 SSM Spring+SpringMVC+Mybatis三大框架的整合实战教程。
开始,先看看我们的最终完成的项目目录结构:
在开始实战整合前,先简单介绍下,目录结果里面的各种配置文件(初学者最怕的无非也就是配置配置配置了,所以SpringBoot遵循习惯优于配置,直接帮忙弄了很多默认配置,让咱们IT搬砖民工沉迷于此无法自拔)
小白文简单讲讲:
web.xml 因为我们做的是一个web项目,这个web.xml是项目一跑起来,我们回去优先加载读取的一个配置文件。也就是说,项目是从它开始入手的,所以一会可以看到这个配置文件里面会有这么一行(加载applicationContext.xml):
<param-value> classpath:spring/applicationContext.xml</param-value>
applicationContext.xml 可以看到我们项目是三大框架的整合,既然是Spring+SpringMVC+Mybatis,那总得有个东西把三大框架整合关联起来吧? 没错,你就这么理解这个applicationContext.xml就是这一条关联的绳子(可以想想其重要性,这是一个基本杂七杂八的配置都在里面过一过那种),我们先瞄一样里面的这几行:
<value>classpath:jdbc.properties</value>
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/>
mybatis.xml 这个配置文件就是针对mybatis框架的。
generator.properties 和 generatorConfig.xml 这两个配置文件不是必须有的,因为这是用于逆向工程的。(不了解不要紧,一会咱们一起用下,你就知道用起来多舒服了。PS:逆向工程,根据数据表直接生成对接数据库层面需要的代码类,包括实体类、Mapper接口、MapperXML sql语句等)
jdbc.properties 这个配置文件里面就是一些连接数据库需要用到的信息(用户名、密码、连接host等等)
log4j.properties 这个配置文件是针对日志打印的。
好了,配置文件大致我们都认识了下,那么我们接下来整合就快很多了,因为现在其实已经知道这个项目大概内容是做啥了。
PS: 千万不要嫌我啰嗦,我这个是真的从零教大家整合,所以会显得比较啰嗦。
开始,首先
空空如也的我们先建一个MAVEN项目,
groupid:我填的 com.springmvc (需要跟后面自己手动建文件夹对应起来)
然后把以下目录结构准备好(因为你建完MAVEN项目,有可能只有个src文件夹和一个webapp文件夹),就是建文件夹以及一些配置文件:
ps:
让一个文件夹带上‘三个横杠’,对着文件夹,鼠标右键,找到make directory as,选择Resources root
让一个文件夹变成蓝色,对着文件夹,鼠标右键,找到 make directory as,选择Sources root
需要用到的文件我们都建完了,那么开始,我们先从依赖包入手,没有依赖包,怎么使用这些框架技术呢,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>com.springmvc</groupId>
<artifactId>elegantjc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>elegantjc Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mybatis-generator-core 反向生成java代码-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>elegantjc</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--允许移动生成的文件-->
<verbose>true</verbose>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
然后jdbc.properties:
driver=com.mysql.jdbc.Driver
#game_message为我本地的数据库名
url=jdbc:mysql://localhost:3306/game_message?useUnicode=true&characterEncoding=utf-8
username=root
#下面输入自己数据库的密码
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
然后log4j.properties:
#log4j.rootLogger=debug,console,debug,info,warn,error,fatal
log4j.rootLogger=INFO,info,warn,error,fatal
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.Encoding=UTF-8
log4j.appender.console.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
#log4j.logger.java.sql.ResultSet=INFO
#log4j.logger.org.apache=INFO
#log4j.logger.java.sql.Connection=INFO
#log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.org.springframework=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.hibernate=ERROR
log4j.logger.com.mchange=ERROR
log4j.logger.org.quartz=ERROR
log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
log4j.appender.debug.datePattern='.'yyyy-MM-dd-HH
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.append=true
log4j.appender.debug.Encoding=UTF-8
log4j.appender.debug.File=${loghome}/mall_debug.log
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
log4j.appender.info.datePattern='.'yyyy-MM-dd-HH
log4j.appender.info.Threshold=INFO
log4j.appender.info.append=true
log4j.appender.info.Encoding=UTF-8
log4j.appender.info.File=${loghome}/mall_info.log
log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
log4j.appender.warn.datePattern='.'yyyy-MM-dd-HH
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.append=true
log4j.appender.warn.Encoding=UTF-8
log4j.appender.warn.File=${loghome}/mall_warn.log
log4j.logger.error=error
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
log4j.appender.error.datePattern='.'yyyy-MM-dd-HH
log4j.appender.error.Threshold=ERROR
log4j.appender.error.append=true
log4j.appender.error.Encoding=UTF-8
log4j.appender.error.File=${loghome}/mall_error.log
log4j.logger.fatal=fatal
log4j.appender.fatal=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fatal.layout=org.apache.log4j.PatternLayout
log4j.appender.fatal.layout.ConversionPattern= %p %d{MM-dd_HH:mm:ss} %F %L %m %n
log4j.appender.fatal.datePattern='.'yyyy-MM-dd-HH
log4j.appender.fatal.Threshold=FATAL
log4j.appender.fatal.append=true
log4j.appender.fatal.Encoding=UTF-8
log4j.appender.fatal.File=${loghome}/mall_fatal.log
#The log output to the directory
#loghome=/log/tomcat/zqgameapi_logs
#loghome=/data/logs/tomcat/admin.gamelaoyou.com
loghome=F:\\log_data
mybatis.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>
<settings>
<setting name="cacheEnabled" value="false" />
<setting name="useGeneratedKeys" value="true" />
<setting name="defaultExecutorType" value="REUSE" />
<!-- 打印MYSQL语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd" >
<!-- ①:对com.springmvc包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.springmvc"/>
<mvc:annotation-driven />
<!-- 静态资源访问 -->
<!--如果webapp下你新建了文件夹,想访问里面的静态资源,那么就要在这配置一下-->
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/styles/" mapping="/styles/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<!-- Configures the @Controller programming model
<mvc:annotation-driven />-->
<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 配置会话工厂SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis.xml" />
<property name="mapperLocations" value="classpath:sqlmap/*Mapper.xml"/>
<property name="typeAliasesPackage" value="com.springmvc.entity" />
</bean>
<!-- 在spring容器中配置mapper的扫描器产生的动态代理对象在spring的容器中自动注册,bean的id就是mapper类名(首字母小写)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描包的路径,就是mapper接口的路径,多个包中间以 半角逗号隔开 -->
<property name="basePackage" value="com.springmvc.dao"/>
<!-- 配置sqlSessionFactoryBeanName -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 配置视图解析器,把控制器的逻辑视频映射为真正的视图 -->
<!-- /WEB-INF/jsp/start.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置dbcp数据库连接池 -->
<!-- <context:property-placeholder location="classpath:db.properties"/> -->
<!--数据库配置 -->
<bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="100"/>
<property name="maxIdle" value="5"/>
<property name="maxWait" value="80000"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 拦截器 -->
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- 定义无Controller的path<->view直接映射 -->
<!-- <mvc:view-controller path="/" view-name="redirect:/" /> -->
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>elegantjc</display-name>
<!-- 配置编码方式-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置springmvc的前端控制器 指向spring-mvc.xml 程序在启动的时候就加载springmvc 可以接受所有请求 load-on-startup:表示启动容器时初始化该Servlet; -->
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以自定义servlet.xml配置文件的位置和名称, 默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 将前端URL请求和后台处理方法controller建立对应关系-->
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring配置 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 取消对某一类文件的拦截-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.md</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> classpath:spring/applicationContext.xml</param-value>
</context-param>
<!-- 欢迎页面-->
<welcome-file-list>
<welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list>
<!--404错误展示页面,可自行配置-->
<!--<error-page>-->
<!--<error-code>404</error-code>-->
<!--<location>/WEB-INF/views/404.jsp</location>-->
<!--</error-page>-->
<!--设置session失效时间为30分钟 -->
<session-config>
<session-timeout>600</session-timeout>
</session-config>
</web-app>
generator.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/game_message?useUnicode=true&characterEncoding=utf-8
username=root
password=root
#entity 包名和 java目录
modelPackage=com.springmvc.entity
modelProject=src/main/java
#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目录
mapperPackage=com.springmvc.dao
mapperProject=src/main/java
#数据库需要自动逆向生成的表的名字
table=messageboard
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>
<!--导入属性配置 -->
<properties resource="generator.properties"/>
<classPathEntry
location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar" />
<context id="context1">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<jdbcConnection driverClass="${driver}"
connectionURL="${url}"
userId="${username}"
password="${password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="${modelPackage}"
targetProject="${modelProject}" />
<sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
<javaClientGenerator targetPackage="${mapperPackage}"
targetProject="${mapperProject}" type="XMLMAPPER" />
<!-- 如果需要通配所有表 直接用sql的通配符 %即可 -->
<table schema="" tableName="${table}" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
到这里,我们其实已经整合完毕了,这时候你需要做的是,先别急着往下看,先回过头看看配置文件里面的注释,了解一下各项配置的作用。
继续,我们现在开始在数据简单建一张表,名字叫messageboard:
表建完了,我们开始打开IDEA右侧的maven模块,找到mybatis-generator,双击它进行逆向工程的生成:
看到控制台出现了 BUILD SUCCESS ,那么你可以看到你的项目,多了三个文件,可以点开看看,增删改查基本都帮你自动生成了(搬砖必备):
好了,那么我们接下来添加service层和controller层代码,这样就是controller->service->dao->entity 四层结构:
MessageBoardService.java:
package com.springmvc.service;
import com.springmvc.entity.Messageboard;
/**
* @Author : JCccc
* @CreateTime : 2019/7/31
* @Description :
**/
public interface MessageboardService {
int insert(Messageboard record);
}
MessageBoardServiceImpl.java:
package com.springmvc.service.impl;
import com.springmvc.dao.MessageboardMapper;
import com.springmvc.entity.Messageboard;
import com.springmvc.service.MessageboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author : JCccc
* @CreateTime : 2019/7/31
* @Description :
**/
@Service
public class MessageboardServiceImpl implements MessageboardService {
@Autowired
MessageboardMapper messageboardMapper;
@Override
public int insert(Messageboard record) {
return messageboardMapper.insert(record);
}
}
然后是controller层:
MessageboardController.java:
package com.springmvc.controller;
import com.springmvc.entity.Messageboard;
import com.springmvc.service.MessageboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author : JCccc
* @CreateTime : 2019/7/31
* @Description :
**/
@RestController
public class MessageboardController {
@Autowired
MessageboardService messageboardServiceImpl;
@RequestMapping(value = "/addMessageBoardData",produces = "application/json; charset=utf-8")
public String addMessageBoardData() {
Messageboard messageboard =new Messageboard();
messageboard.setUsername("测试添加");
messageboard.setMessage("哇,SSM整合这么简单");
int effectNum = messageboardServiceImpl.insert(messageboard);
int id=messageboard.getId();
System.out.println();
return "影响行数:"+effectNum+" 返回主键id:"+id;
}
}
可以看到我这个接口里面,调用的方法是插入方法。
那么我们将项目跑起来(配置下tomcat),最后用Postman去调这个接口测试下:
看下控制台:
看下数据库表数据:
好了,到这里,这篇教程就真的到此结束了,希望你能收获到些什么(PS: 不用自动生成,自己去手写mapper、mapper.xml、pojo都是非常正常的,喜欢自己建的完全可以自己建,喜欢自动生成的就可以用自动生成)。