SSM整合记录
就想自己折腾,把框架聚合起来,然后发现公司的框架配置,其实官网基本都写详细了。
结合官网文档,很快可以搭出来的。不懂再看下公司项目配置,美滋滋....
参考文档:
proxool: http://proxool.sourceforge.net/index.html
mybatis: http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html
mybatis-spring: http://www.mybatis.org/spring/zh/mappers.html
1.先来全家福:
以及数据库:
2. pom.xml配置:
<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.renzku</groupId> <artifactId>myssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>myssm</name> <url>http://maven.apache.org</url> <properties> <!-- 文件的编码 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- 编译时的编码 --> <maven.compiler.encoding>UTF-8</maven.compiler.encoding> <javax.version>1.7</javax.version> <taglibs.standard.version>1.1.2</taglibs.standard.version> <javaee.web.api.version>7.0</javaee.web.api.version> <jsp.api.version>2.2</jsp.api.version> <proxool.version>0.9.1</proxool.version> <mybatis.version>3.4.5</mybatis.version> <mybatis.spring.version>1.3.1</mybatis.spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--Object/Xml Mappers 这里没用,但没删,防止忘记--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- spring事务的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <!-- 事务有用到切面 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <!-- spring-aspects依赖于aspectjweaver ;所以不添加了--> <!--<dependency>--> <!--<groupId>org.aspects</groupId>--> <!--<artifactId>aspectjweaver</artifactId>--> <!--</dependency>--> <!-- 数据库这边的依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <!--mybatis的2个依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- 不用proxool原始那个,依赖servlet-api有点问题 --> <dependency> <groupId>org.logicalcobwebs</groupId> <artifactId>com.springsource.org.logicalcobwebs.proxool</artifactId> <version>${proxool.version}</version> </dependency> <!-- mysqldriver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 配置taglibs 和 jstl --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs.standard.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- 其它web依赖 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>${javaee.web.api.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.api.version}</version> </dependency> <!-- 对json和xml的格式支持 --><!-- requestMapping设置produces=application/xml等就可以格式化 --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names --> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> </dependency> <!-- 文件上传 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> <!-- 简化io操作 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <!-- 其他Commons --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <!-- spring 提供的版本管理,他会选择他默认的版本下载下来 --> <dependency> <groupId>io.spring.platform</groupId> <artifactId>platform-bom</artifactId> <version>Brussels-SR4</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <finalName>myssm</finalName> </build> </project>
3. web.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring-application.xml, classpath*:spring-mybatis.xml </param-value> </context-param> <servlet> <servlet-name>dispatcher</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> <!-- 注意 /XX/* /* *.XX 的区别(* 和/*.do 报错了,为什么呢)--> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/hehe/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 编码 --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4. spring-application.xml 这里只用来了扫描service和dao 注解:
<?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" 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"> <!-- Bean 扫描,过滤Controller(这个在spring-mvc.xml里扫描) --> <context:component-scan base-package="com.renzku"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
5. spring-mvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描Controller Bean,注意以后改时:加载mvc扫描Controller时都要把service排出去(虽然这里这包下没service),否则可能事务不起作用--><context:component-scan base-package="com.renzku.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <mvc:annotation-driven enable-matrix-variables="true"/> <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/> <!-- 请求的接受类型设置 --> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="favorPathExtension" value="false" /> <property name="favorParameter" value="true" /> <property name="defaultContentType" value="text/html" /> <property name="useJaf" value="false" /> <property name="ignoreAcceptHeader" value="false" /> <property name="ignoreUnknownPathExtensions" value="false" /> <property name="mediaTypes"> <value> json=application/json xml=application/xml </value> </property> </bean> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper" ref="objectMapper"/> </bean> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"> <property name="objectMapper" ref="xmlMapper"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd" p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/> <bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </list> </property> </bean> <!-- 静态资源过滤 --> <mvc:resources mapping="/resources/**" location="/resources/"/> <!-- springmvc文件上传配置所需类导入 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> </bean> </beans>
6. jdbc.properties:
db.driver=com.mysql.jdbc.Driver db.host=localhost db.databaseName=myssm db.url=jdbc:mysql://${db.host}:3306/${db.databaseName}?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull db.username=root db.password=123456 db.maximum.connection.count=100 db.minimum.connection.count=1 db.simultaneous.build.throttle=3
7.mybatis-config.xml,这些个属性含义,mybatis官网很详细:
<?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="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="true"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="2500"/> <setting name="defaultFetchSize" value="100"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="mapUnderscoreToCamelCase" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="NULL"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/> </settings> </configuration>
8.spring-mybatis.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: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/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"> <!-- 加载jdbc配置文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:jdbc.properties"/> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="alias" value="proxoolDataSource"/> <property name="driver" value="${db.driver}"/> <property name="driverUrl" value="${db.url}"/> <property name="user" value="${db.username}"/> <property name="password" value="${db.password}"/> <property name="maximumConnectionCount" value="${db.maximum.connection.count}"/> <property name="minimumConnectionCount" value="${db.minimum.connection.count}"/> <property name="simultaneousBuildThrottle" value="${db.simultaneous.build.throttle}"/> </bean> <!-- SqlSessionFactory配置和加载mapper映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath*:config/mapper/**/*.xml"/> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <constructor-arg index="1" value="BATCH" /> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- the transactional semantics... --> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- ensure that the above transactional advice runs for any execution of an operation defined by the FooService interface --> <aop:config> <aop:pointcut id="fooServiceOperation" expression="execution(* com.renzku.service..*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/> </aop:config> </beans>
9.实体类SysUser.java:
package com.renzku.POJO; /** * Created by renzku on 2017/9/9. */ public class SysUser { private Long userId; private String userName; private String userText; public SysUser() { } public SysUser(Long userId, String userName, String userText) { this.userId = userId; this.userName = userName; this.userText = userText; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserText() { return userText; } public void setUserText(String userText) { this.userText = userText; } }
10.userMapper.xml映射文件:
<?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="renkzu.config.mapper.userMapper"> <resultMap id="commonResult" type="com.renzku.POJO.SysUser"> <result column="user_id" property="userId" jdbcType="BIGINT"/> <result column="user_name" property="userName" jdbcType="VARCHAR"/> <result column="user_text" property="userText" jdbcType="VARCHAR"/> </resultMap> <select id="findSysUserAllList" resultMap="commonResult"> SELECT * from myssm_user </select> </mapper>
11.SysUserDaoImpl.java:
这里说下,这里配置数据库访问用的SqlSessionDaoSupport。
所以在访问时(比如selectList(String namespace [,Object obj])),至少需要传入mapper.xml的namespace;
所以这里的findSysUserAllList()中sqlName变量为 "renzku.config.mapper.userMapper.XX",与userMapper.xml中的namespace一致;
就是:
1.这个可以随便取名字,只要两处保持相同即可;
2.有另外一种配置方式:不用SqlSessionDaoSupport的,只写Dao的 interface,然后跟userMapper.xml关联,这个userMapper.xml就必须写Dao的包路径加文件名称。
package com.renzku.dao.impl; import com.renzku.POJO.SysUser; import com.renzku.dao.SysUserDao; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by renzku on 2017/9/9. */ @Repository public class SysUserDaoImpl extends SqlSessionDaoSupport implements SysUserDao { @Autowired @Override public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { super.setSqlSessionTemplate(sqlSessionTemplate); } public List<SysUser> findSysUserAllList() { String sqlName="renkzu.config.mapper.userMapper"+".findSysUserAllList"; return this.getSqlSession().selectList(sqlName); } }
12.HelloWorldController.java:
package com.renzku.controller; import com.renzku.POJO.SysUser; import com.renzku.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; /** * Created by renzku on 2017/9/6. */ @Controller public class HelloWorldController { @Autowired private SysUserService sysUserService; @RequestMapping(value = "/helloWorld") public String helloWorld(Model model) { // 直接一直调用到SysUserDaoImpl.findSysUserAllList List<SysUser> userlist=this.sysUserService.findSysUserAllList(); model.addAttribute("ssm", userlist.get(0)); return "helloWorld"; } }
13.helloWorld.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <h2>Hello World!</h2> <h3>yayaay:${ssm.userName}</h3> </body> </html>
14.效果:
访问 http://localhost:8081/myssm/hehe/helloWorld
显示 :
15. 源码下载
链接: https://pan.baidu.com/s/1ge5b24z 密码: fpnf
------------------------------------------------------------------------------------------------------------------------------------
20170909:
上面spring-mybatis.xml事务配置那里,没完成呢。
添加 rollback-for才行,添加后,service方法中抛出对应异常,则可以引起事务回滚。
另外IllegalArgumentException继承自Exception,抛出它也会引起rollback-for=“Exception”的回滚。
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <!-- the transactional semantics... --> <tx:attributes> <!-- all methods starting with 'get' are read-only --> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="update*" rollback-for="Exception"/> <tx:method name="delete*" rollback-for="IllegalArgumentException"/> <!-- other methods use the default transaction settings (see below) --> <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/> </tx:attributes> </tx:advice>