SSM(Spring+SpringMVC+Mybatis)整合
@TOC
一、SSM(Spring+SpringMVC+Mybatis)框架的整合流程
使用Spring+SpringMVC+Mybatis 框架技术进行整合;
SpringMVC:运用在表现层
MyBatis:运用在持久层
Spring:运用在整个项目中
二、搭建流程
1、使用maven的方式导入所有的jar包
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lixiang</groupId>
<artifactId>ssm</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ssm Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.3.10.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 导入junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 导入common-lang辅助包 -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- 导入jstl相关的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 导入servlet的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<!-- 导入C3P0连接池的jar包 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- 导入mysql的驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<!-- 导入spring的核心jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring -web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 导入spring的jdbc相关的jar,主要用来处理事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 导入spring中aop相关jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 实现jsr303,用于参数校验 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- 引入jackson 的jar包,用来返回json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!-- 文件是上传的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- 导入mybatis跟spring的适配包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 导入mybatis的jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- 导入mybatis 跟ehcache的适配包-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!-- 导入日志相关的jar包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 导入mybatis代码生成器的jar包 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
<scope>test</scope>
</dependency>
<!-- 引入分页的jar包 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
</dependencies>
<build>
<!-- 项目名称 -->
<finalName>ssm</finalName>
</build>
</project>
2、在web.xml环境中配置springMVC和Spring的启动
Web.xml中的文件内容如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- spring 文件的地址配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 指定spring的配置文件 -->
<param-value>classpath:application.xml</param-value>
</context-param>
<!-- 配置spring容器的启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置映射路径 -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3、 Spring和SpringMVC的配置文件
1). Spring的配置文件
文件名称:application.xml 放在resources目录下,内容如下:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置自动扫描 -->
<context:component-scan base-package="com.lixiang.ssm">
<!-- 排除表现层的内容 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
<!-- 配置跟事务处理有关 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 使用注解的方式来处理事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 注册sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 指定mybatis的配置文件的地址 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 导入映射文件的地址,映射文件统一放在mapper文件夹下面 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml"></property>
<!-- 注意其他配置 -->
<property name="plugins">
<array>
<!-- 配置分页插件 -->
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
helperDialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- 把包下面的接口的代理对象让IOC容器管理 ,base-package:指定mybatis映射文件接口类所在jar包-->
<mybatis-spring:scan base-package="com.lixiang.ssm.dao"/>
</beans>
2). SpringMVC的配置文件
文件名称:spring-mvc.xml 放在resources目录下
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd">
<!-- 配置自动扫描 -->
<context:component-scan base-package="com.lixiang.ssm"
use-default-filters="false">
<!-- 只包含表现层的内容 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- 配置跟视图有关 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置国际化资源管理 -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>
<!-- 配置文件上传的 处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设置上传的单个文件大小 限制,单位:字节 最大10M -->
<property name="maxUploadSizePerFile" value="#{10*1024*1024}"></property>
</bean>
<!-- 访问静态资源 -->
<mvc:default-servlet-handler />
<!-- 开发一般要加上 -->
<mvc:annotation-driven />
</beans>
4、Mybatis的配置文件
文件名称:mybaits-config.xml 放在resources目录下
<?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="mapUnderscoreToCamelCase" value="true" />
<!-- 开启懒加载 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 开启、关闭 二级缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 指定日志 -->
<setting name="logImpl" value="LOG4J" />
</settings>
</configuration>
5、Ehcache的配置文件
文件名称:ehcache.xml 放在resources目录下
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir" />
<!-- Mandatory Default Cache configuration. These settings will be applied
to caches created programmtically using CacheManager.add(String cacheName) -->
<!-- name:缓存名称。 maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk
store persists between restarts of the Virtual Machine. The default value
is false. diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。 -->
<defaultCache maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
6、其他配置文件
请自行导入DB.propeprties和log4j.properties,注意存放的路径
三、使用事项
1.使用ehcache缓存
开启mybatis的二级缓存,在需要使用cache的映射文件中加入标签
内容如下:
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<property name="timeToIdleSeconds" value="3600" /><!--1 hour -->
<property name="timeToLiveSeconds" value="3600" /><!--1 hour -->
<property name="maxEntriesLocalHeap" value="1000" />
<property name="maxEntriesLocalDisk" value="10000000" />
<property name="memoryStoreEvictionPolicy" value="LRU" />
</cache>
2.使用mybatis代码生成工具
用来自动生成实体类,mapper接口,以及mapper映射文件
- 代码生成工具的的配置文件
文件名称:mybatis-generator.xml ,
注意放在test目录的resources中,因为该配置只是在开发中需要用到,实际运行中是不需要的
内容如下:
<?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>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 数据类的连接配置 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mvc" userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定实体类的路径,targetPackage=包名, targetProject=项目的实际地址-->
<javaModelGenerator targetPackage="com.lixiang.mybatis.entity"
targetProject="D:\software\eclipse\workspace5\mybatis2\src\main\java">
<property name="constructorBased" value="true"/>
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定映射文件的路径 ,targetPackage=包名, targetProject=项目的实际地址 -->
<sqlMapGenerator targetPackage="com.lixiang.mybatis.dao"
targetProject="D:\software\eclipse\workspace5\mybatis2\src\main\java">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定生成接口路径 -,targetPackage=包名, targetProject=项目的实际地址 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.lixiang.mybatis.dao" targetProject="D:\software\eclipse\workspace5\mybatis2\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 配置需要生成那个表,table=表名,domainObjectName=对象名 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
<!-- 自定义字段生成规则 -->
<columnOverride column="money" property="money" javaType="java.lang.Double" />
<columnOverride column="type" property="type" javaType="java.lang.Integer" />
</table>
</context>
</generatorConfiguration>
- 执行生成
在test目录下建立一个类,建立一个main方法
内容如下:
public class MybatisGenerator {
public static void main(String[] args) throws Exception{
// 用来封装警告信息
List<String> warnings = new ArrayList<>();
// 是否覆盖
boolean overwrite = true;
// 类路径下面
InputStream is = MybatisGenerator.class.getClassLoader().getResourceAsStream("mybatis-generator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config;
// 解析配置文件
config = cp.parseConfiguration(is);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println("打印警告信息....................");
for (String warn : warnings) {
System.out.println(warn);
}
}
注意:如果jar包有问题,请核实自己的本地库是否有问题。