使用Maven搭建Spring+SpringMVC+Mybatis+ehcache项目

搭建Spring不用说肯定是必须的,前端使用SpringMVC 而不使用Struts2是因为SpringMVC的效率要比struts2要高很多,虽然struts2有丰富的标签可以使用,
使用Mybatis是因为以后项目要做报表模块,Mybatis使用SQL Mapping的方式很容易操作数据库。

这里我们使用intellij idea来做我们的开发工具,废话不多说,开干。
框架的版本是

Spring 3.2.8.RELEASE
Spring MVC 3.2.8.RELEASE
mybatis 3.2.8

一、创建Maven Web项目

(略)
本项目中用的maven是 3.3.3版本的,要求jdk版本是1.7之后的

二、在pom.xml中加入项目依赖的jar包

项目包依赖关系如下:

pom文件如下:

    

        
        1.7
        UTF-8
        UTF-8

        
        2.2
        1.2
        3.0.1


        
        3.2.8.RELEASE


        
        1.7.5
        
        4.11

    

    


        
        
            org.aspectj
            aspectjrt
            1.8.7
        

        
            org.aspectj
            aspectjweaver
            1.8.7
        


        
        
            org.springframework
            spring-webmvc
            ${spring-framework.version}
        

        
        
            org.springframework
            spring-tx
            ${spring-framework.version}
        

        
            org.springframework
            spring-jdbc
            ${spring-framework.version}
        

        
            org.springframework
            spring-test
            ${spring-framework.version}
            test
        

        
        
            org.springframework
            spring-tx
            ${spring-framework.version}
        

        
            org.springframework
            spring-web
            ${spring-framework.version}
        


        
        
            org.slf4j
            slf4j-api
            ${slf4j.version}
            compile
        

        
            org.slf4j
            slf4j-log4j12
            1.7.12
        

        
        
            org.mybatis
            mybatis-spring
            1.2.2
        

        
            org.mybatis
            mybatis
            3.2.8
        

        
            org.mybatis
            mybatis-ehcache
            1.0.0
        


        
            mysql
            mysql-connector-java
            5.1.34
        


        
            junit
            junit
            ${junit.version}
            test
        

        
        
            commons-dbcp
            commons-dbcp
            1.4
        
        
            commons-lang
            commons-lang
            2.5
        

        
        
            javax.servlet
            jstl
            ${jstl.version}
        


        
            javax.servlet
            javax.servlet-api
            ${servlet.version}
            provided
        

        
            javax.servlet.jsp
            jsp-api
            ${jsp.version}
            provided
        

        
            org.apache.taglibs
            taglibs-standard-impl
            1.2.3
        

    

三、添加日志的支持

日志我们使用slf4j,并用log4j来实现
SLF4J不同于其他日志类库,与其它有很大的不同。SLF4J(Simple logging Facade for Java)不是一个真正的日志实现,而是一个抽象层( abstraction layer),它允许你在后台使用任意一个日志类库。
SLF4J还有很多优点,具体可以参考 http://javarevisited.blogspot.com/2013/08/why-use-sl4j-over-log4j-for-logging-in.html
日志的实现类还是用熟悉的log4j,先要在项目的pom.xml文件中加入日志的支持

        
        
            org.slf4j
            slf4j-api
            1.7.5
            compile
        

        
            org.slf4j
            slf4j-log4j12
            1.7.12
        

配置很简单,log4j的详细配置可以参考log4j官网

log4j.properties

log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Threshold = DEBUG
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d %p [%c]  - %m%n


log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.File=${catalina.home}/logs/
log4j.appender.A2.Append=false
log4j.appender.A2.DatePattern='-'yyyy-MM-dd'.log'
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d %p [%c] - %m%n

三、整合Spring+Mybatis

把Spring和Mybatis的jar包都引入之后就可以整合这两个框架了
先看下项目的相关配置文件
其中gererator.properties和generatorConfig.xml是用来根据数据库自动生成mapper接口,实体,以及映射文件的
mybatis-config是mybatis的一些映射的相关配置,比如mapper,cache等
spring-mybatis是自动扫描,自动装配mapper以及datasource,sqlSessionFactory等配置

这些会在接下来详细说明

1.JDBC配置文件

jdbc.initialSize=5
jdbc.maxActive=20
jdbc.maxIdle=5
jdbc.defaultAutoCommit=true
jdbc.removeAbandoned=true  
jdbc.removeAbandonedTimeout=30 
jdbc.logAbandoned=true
jdbc.testWhileIdle=true
jdbc.validationQuery=select 1 from dual
jdbc.timeBetweenEvictionRunsMillis=30000
jdbc.numTestsPerEvictionRun=10
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

2.创建spring-mybatis.xml

创建spring-mybatis.xml来配置mybatis的一些信息,主要是数据源、事务、自动扫描、自动注入等功能


 xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
     base-package="com.zeusjava" />

    
     />

    
     />

    
     id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         name="location" value="classpath:jdbc.properties" />
    
    
    
     id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
         name="driverClassName" value="${jdbc.driverClassName}" />
         name="url" value="${jdbc.url}" />
         name="username" value="${jdbc.username}" />
         name="password" value="${jdbc.password}" />
         name="initialSize" value="${jdbc.initialSize}" />
         name="maxActive" value="${jdbc.maxActive}" />
         name="maxIdle" value="${jdbc.maxIdle}" />
         name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}" />
         name="removeAbandoned" value="true" />
         name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
         name="logAbandoned" value="${jdbc.logAbandoned}" />
        
         name="testWhileIdle"  value="${jdbc.testWhileIdle}" />
         name="validationQuery" value="${jdbc.validationQuery}" />
         name="timeBetweenEvictionRunsMillis"  value="${jdbc.timeBetweenEvictionRunsMillis}" />
         name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}" />
    

     id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         name="dataSource" ref="dataSource"/>
        
         name="typeAliasesPackage" value="com.zeusjava.kernel.entity"/>
        
         name="configLocation" value="classpath:mybatis-config.xml"/>
        
         name="mapperLocations" value="classpath*:com/zeusjava/kernel/mapper/*.xml"/>
    

    
     class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         name="basePackage" value="com.zeusjava.kernel.dao"/>
    

     id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
         ref="sqlSessionFactory"/>
    

     id="mybatisTransactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
          p:dataSource-ref="dataSource"/>

     id="txAdvice" transaction-manager="mybatisTransactionManager">
        
             name="save*" propagation="REQUIRED"/>
             name="insert*" propagation="REQUIRED"/>
             name="add*" propagation="REQUIRED"/>
             name="update*" propagation="REQUIRED"/>
             name="delete*" propagation="REQUIRED"/>
             name="remove*" propagation="REQUIRED"/>
             name="accept*" propagation="REQUIRED"/>
             name="reject*" propagation="REQUIRED"/>
             name="execute*" propagation="REQUIRED"/>
             name="del*" propagation="REQUIRED"/>
             name="recover*" propagation="REQUIRED"/>
             name="sync*" propagation="REQUIRED"/>
             name="*" read-only="true"/>
        
    

    
         id="txPointcut"
                      expression="execution(public * com.zeusjava.kernel.service.*.*(..))"/>
         pointcut-ref="txPointcut" advice-ref="txAdvice"/>
    

3.创建数据库表

  CREATE TABLE `user` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `user_name` varchar(40) NOT NULL,  
  `password` varchar(255) NOT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  


insert  into `user`(`id`,`user_name`,`password`) values (1,'赵宏轩','123456');  

4.创建User的Mapping映射文件,User实体和Mapper接口

1.在pom.xml中添加mybatis-generator-maven-plugin插件

  
    HelloSSM
    
      
        org.mybatis.generator
        mybatis-generator-maven-plugin
        1.3.2
        
          true
          true
        
      
    
  
``
`

####2.在maven项目下的src/main/resources 目录下建立名为 generatorConfig.xml的配置文件以及和generator有关的属性文件,作为mybatis-generator-maven-plugin 插件的执行目标

![目录结构](http://i13.tietuku.com/274205a36b4c55d5.png)
 generatorConfig.xml

 ```xml
 

        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

    
     resource="generator.properties">
    
     location="${jdbc.driverLocation}"/>
     id="default" targetRuntime="MyBatis3">
        
        
             name="suppressDate" value="true" />
        
        
         driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
        
         >
             name="forceBigDecimals" value="false" />
        
         targetPackage="com.zeusjava.kernel.entity" targetProject="src/main/java">
            
             name="constructorBased" value="true"/>
            
             name="enableSubPackages" value="false"/>
            
             name="immutable" value="true"/>
             name="trimStrings" value="true"/>
        

        
         targetPackage="com.zeusjava.kernel.mapper" targetProject="src/main/java">
             name="enableSubPackages" value="false"/>
        

         targetPackage="com.zeusjava.kernel.dao" targetProject="src/main/java" type="MIXEDMAPPER">
             name="enableSubPackages" value=""/>
             name="exampleMethodVisibility" value=""/>
             name="methodNameCalculator" value=""/>
             name="rootInterface" value=""/>
        

         tableName="user"
               domainObjectName="User"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">

        
    

还有与之相关联的generator.properties文件

jdbc.driverLocation=D:\\idea\\maven\\mysql\\mysql-connector-java\\5.1.29\\mysql-connector-java-5.1.29.jar
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

3.在Intellij IDEA添加一个“Run运行”选项,使用maven运行mybatis-generator-maven-plugin插件

1).点击Run,选择Edit Configurations

2).点击左上角的+,选择maven

3).输入name,选择Working directory,Command line 填上mybatis-generator:generate -e

4.点击运行查看结果

运行插件控制台如果打印build Success 就说明成功了

会在指定目录产生三个文件,分别是实体Mapper接口Mapping配置文件

5.创建mybatis-config.xml配置文件



        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

       
               name="cacheEnabled" value="false"/>
               name="lazyLoadingEnabled" value="true"/>
               name="aggressiveLazyLoading" value="false"/>
               name="localCacheScope" value="STATEMENT"/>
               name="multipleResultSetsEnabled" value="true"/>
               name="useColumnLabel" value="true"/>
               name="defaultStatementTimeout" value="25000"/>
               name="mapUnderscoreToCamelCase" value="true"/>
              
               name="useGeneratedKeys" value="true"/>
       

       
               alias="User" type="com.zeusjava.kernel.entity.User" />
       

       
              
              
              
               name="com.zeusjava.kernel.dao"/>
              

       

其中最后的mapper有四种配置方式,但是,在我的电脑上只有使用url的方式才行,不知道是怎么回事,待查询。

6.建立Service接口和实现类

IUserService.java代码如下

package com.zeusjava.kernel.service;

import com.zeusjava.kernel.entity.User;

/**
 * Created by LittleXuan on 2015/10/17.
 */
public interface IUserService {
    public User getUserById(int userId);
}

UserServiceImpl.java的代码如下

package com.zeusjava.kernel.service.impl;

import com.zeusjava.kernel.dao.UserMapper;
import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by LittleXuan on 2015/10/17.
 */
@Service("userService")
public class IUserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(int userId) {
        return this.userMapper.selectByPrimaryKey(userId);
    }
}

7.建立测试类

import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Created by LittleXuan on 2015/10/17.
 */
@RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath:conf/spring/beans-mybatis.xml"})
public class SSMTest {
    private static Logger logger = LoggerFactory.getLogger(SSMTest.class);

    @Resource
    private IUserService userService = null;


    @Test
    public void test1() {
        User user = userService.getUserById(1);
        logger.info("姓名:"+user.getUserName());
    }
}

运行单元测试,结果如下,说明spring和mybatis的整合已经完成。

四、和SpringMVC整合

和Spring MVC的整合就简单的多了,只需要添加一个Spring MVC配置文件,和配置一下Web.xml就行了,我在前面的博客写过一篇文章,请戳 Maven整合Spring MVC搭建笔记-ZeusJava Blog

1.配置Spring MVC 配置文件zeusjava-servlet.xml


在配置文件里主要配置 自动扫描控制器视图解析器注解


 xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd
  ">
    
     />

    
     base-package="com.zeusjava.web.controller"/>

     
     class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    
     class="org.springframework.web.servlet.view.InternalResourceViewResolver"  p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>


2.配置web.xml

在web.xml里配置Spring MVC的DispatcherServlet和mybatis的配置文件


 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">
    HelloSSM
    
    
        contextConfigLocation
        classpath:spring-mybatis.xml
    
    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        true
        
            encoding
            UTF-8
        
    
    
        encodingFilter
        /*
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        org.springframework.web.util.IntrospectorCleanupListener
    

    
    
        SpringMVC
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring-mvc.xml
        
        1
        true
    
    
        SpringMVC
        /
    
    
        /index.jsp
    

  

3.在WEB_INF/jsp建立一个简单的测试页面user.jsp

<%@ page language="java" pageEncoding="UTF-8"%>


用户ID为${user.id}的用户详情

ID:${user.id} 姓名:${user.userName}

4.建立User控制器

通过url传入一个id,解析这个id然后查询数据库,得到User对象放入jsp页面显示。

package com.zeusjava.web.controller;

/**
 * Created by LittleXuan on 2015/10/18.
 */
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.zeusjava.kernel.entity.User;
import com.zeusjava.kernel.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @RequestMapping(value="/userInfo/{id}", method= RequestMethod.GET)
    public String toIndex(HttpServletRequest request, Model model,@PathVariable("id") String id) {
        if(StringUtils.isEmpty(id)){
            throw new IllegalArgumentException("id不能为空");
        }
        int userId = Integer.parseInt(id);
        User user = this.userService.getUserById(userId);
        model.addAttribute("user", user);
        return "user";
    }
}

5.添加tomcat服务器并部署war包

1.File-Project Structure点击Artifacts一栏

点击+,选择Web-Application-Exploded然后选择from maven选中本项目
Web Application Exploded是没有压缩的war包,相当于文件夹
Web Application Achieved是雅俗后的war包

2.intellij会自动帮我们生成一个war包

3.点击Run-Run Configurations

点击+选择tomcat server->local

4.点击Configure

5.点击Deployment选项卡,点击+号,选择一个artifact,就是第二部的war包

6.OK启动服务器

在任务栏输入http://localhost:8081/HelloSSM/user/userInfo/1,回车,结果如下:
一个简单的SSM项目环境就搭建好了。

五、和ehcache的整合

Ehcache是Hibernate的默认的cache,但是mybatis中需要自己集成,在Mybatis中使用会大大增加性能,下面开始整合mybatis和Ehcache

1.使用首先要把需要的jar包依赖加入pom中

 
            org.mybatis
            mybatis-ehcache
            1.0.0
 
 
            org.ehcache
            ehcache
            3.0.0.m3
 

2.在Resource中添加一个ehcache.xml的配置文件


 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
        path="java.io.tmpdir" />
        eternal="false" maxElementsInMemory="1000"
                     overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
                     timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" />
        name="testCache" eternal="false" maxElementsInMemory="100"
              overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
              timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" />

说明:

name:Cache的唯一标识  
maxElementsInMemory:内存中最大缓存对象数  
maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大  
eternal:Element是否永久有效,一但设置了,timeout将不起作用  
overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中  
timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大  
timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大   
diskPersistent:是否缓存虚拟机重启期数据  
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒  
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区  
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)   

3.在spring-mybatis.xml中加入chache配置

    
     id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
         name="configLocation" value="classpath:ehcache.xml" />
    

4.在mapper.xml中配置cache

 type="org.mybatis.caches.ehcache.LoggingEhcache" >  
     name="timeToIdleSeconds" value="3600"/>
     name="timeToLiveSeconds" value="3600"/>
     name="maxEntriesLocalHeap" value="1000"/>  
     name="maxEntriesLocalDisk" value="10000000"/>  
     name="memoryStoreEvictionPolicy" value="LRU"/>  

type是使用的cache类型,LoggingEhcache会记录下日志,如果不需要日志的话可以使用EhcacheCache
这样配置之后,所以的操作都会执行缓存,如果有的操作不需要的话,可以在sql配置里将useCache设置为false

    @Select({
        "select",
        "id, user_name, password",
        "from user",
        "where id = #{id,jdbcType=INTEGER}"
    })
    @Options(useCache = false,timeout = 10000,flushCache = false)
    @ResultMap("BaseResultMap")
    User selectByPrimaryKey(Integer id);

5.测试性能

测试代码

 @Test
    public void test1() {
        long beginTime=System.nanoTime();
        User user = userService.getUserById(1);
        long endTime=System.nanoTime();
        System.out.println("查询时间 :" + (endTime-beginTime)+"ns");
        logger.info("姓名:"+user.getUserName());
    }

第一次把useCache设置为false

第二次把useCache设置为true

两次执行的时间差了大约0.4

整个项目已经放到github上了,有需要的可以前往HelloSSM查看, 不懂的地方欢迎探讨...

转载链接:http://zeusjava.com/2015/10/18/build-an-maven-spring-mybatis-ehcache-web-project/

你可能感兴趣的:(JAVA基础)