Spring + SpringMVC + mybatis + maven + junit

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.0modelVersion>
    <groupId>sy.testmybatisgroupId>
    <artifactId>testmybatisartifactId>
    <packaging>warpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>testmybatis Maven Webappname>
    <url>http://maven.apache.orgurl>
    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>3.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>3.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>3.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.1.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.1.1version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.21version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>0.2.9version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.7.1version>
        dependency>
        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.11version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>3.0-alpha-1version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.26version>
        dependency>
    dependencies>
    <build>
    build>
project>

spring.xml


<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

    
    <context:property-placeholder location="classpath:config.properties" />

    
    <context:component-scan base-package="sy.service" />


beans>

spring-mybatis.xml


<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-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/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

    
    

    
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        
        <property name="initialSize" value="0" />
        
        <property name="maxActive" value="20" />
        
        <property name="maxIdle" value="20" />
        
        <property name="minIdle" value="0" />
        
        <property name="maxWait" value="60000" />

        

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        
        <property name="removeAbandoned" value="true" />
        
        <property name="removeAbandonedTimeout" value="1800" />
        
        <property name="logAbandoned" value="true" />

        
        
        <property name="filters" value="mergeStat" />
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        
        <property name="mapperLocations" value="classpath:sy/mapping/*.xml" />
    bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="sy.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    

    
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        tx:attributes>
    tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    aop:config>


    
    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>sy.service.*value>
            list>
        property>
    bean>
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    aop:config>

beans>

spring-mvc.xml


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    
    <context:component-scan base-package="sy.controller" />

    
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" />

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding">
            <value>UTF-8value>
        property>
        <property name="maxUploadSize">
            <value>32505856value>
        property>
        <property name="maxInMemorySize">
            <value>4096value>
        property>
    bean>

beans>

log4j.properties,开发用DEBUG,生产用INFO或者ERROR

log4j.rootLogger=DEBUG,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=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

log4j.appender.File=org.apache.log4j.RollingFileAppender 
log4j.appender.File.File=mybatis.log
log4j.appender.File.MaxFileSize=10MB
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,SSS}][%c]%m%n

jdbc.properties

jdbc_url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=123456

UserController.java

package sy.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import sy.model.User;
import sy.service.UserServiceI;

@Controller
@RequestMapping("/userController")
public class UserController {

    private UserServiceI userService;

    public UserServiceI getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }

    @RequestMapping("/{id}/showUser")
    public String showUser(@PathVariable String id, HttpServletRequest request) {
        User u = userService.getUserById(id);
        request.setAttribute("user", u);
        return "showUser";
    }

}

UserMapper.xml

version="1.0" encoding="UTF-8" ?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
"sy.dao.UserMapper">
    id="BaseResultMap" type="sy.model.User">
        <id column="ID" property="id" jdbcType="VARCHAR" />
        <result column="CREATEDATETIME" property="createdatetime" jdbcType="TIMESTAMP" />
        <result column="MODIFYDATETIME" property="modifydatetime" jdbcType="TIMESTAMP" />
        <result column="NAME" property="name" jdbcType="VARCHAR" />
        <result column="PWD" property="pwd" jdbcType="VARCHAR" />
        <result column="CREATE_TIME" property="createTime" jdbcType="DATE" />
        <result column="UPDATE_TIME" property="updateTime" jdbcType="DATE" />
    
    id="Base_Column_List">
        ID, CREATEDATETIME, MODIFYDATETIME, NAME, PWD, CREATE_TIME, UPDATE_TIME
    
    
    id="deleteByPrimaryKey" parameterType="java.lang.String">
        delete from tuser
        where ID = #{id,jdbcType=VARCHAR}
    
    id="insert" parameterType="sy.model.User">
        insert into tuser (ID, CREATEDATETIME, MODIFYDATETIME,
        NAME, PWD, CREATE_TIME,
        UPDATE_TIME)
        values (#{id,jdbcType=VARCHAR}, #{createdatetime,jdbcType=TIMESTAMP}, #{modifydatetime,jdbcType=TIMESTAMP},
        #{name,jdbcType=VARCHAR}, #{pwd,jdbcType=VARCHAR}, #{createTime,jdbcType=DATE},
        #{updateTime,jdbcType=DATE})
    
    id="insertSelective" parameterType="sy.model.User">
        insert into tuser
        "(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                ID,
            if>
            <if test="createdatetime != null">
                CREATEDATETIME,
            if>
            <if test="modifydatetime != null">
                MODIFYDATETIME,
            if>
            <if test="name != null">
                NAME,
            if>
            <if test="pwd != null">
                PWD,
            if>
            <if test="createTime != null">
                CREATE_TIME,
            if>
            <if test="updateTime != null">
                UPDATE_TIME,
            if>
        
        "values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=VARCHAR},
            if>
            <if test="createdatetime != null">
                #{createdatetime,jdbcType=TIMESTAMP},
            if>
            <if test="modifydatetime != null">
                #{modifydatetime,jdbcType=TIMESTAMP},
            if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            if>
            <if test="pwd != null">
                #{pwd,jdbcType=VARCHAR},
            if>
            <if test="createTime != null">
                #{createTime,jdbcType=DATE},
            if>
            <if test="updateTime != null">
                #{updateTime,jdbcType=DATE},
            if>
        
    
    id="updateByPrimaryKeySelective" parameterType="sy.model.User">
        update tuser
        <set>
            <if test="createdatetime != null">
                CREATEDATETIME = #{createdatetime,jdbcType=TIMESTAMP},
            if>
            <if test="modifydatetime != null">
                MODIFYDATETIME = #{modifydatetime,jdbcType=TIMESTAMP},
            if>
            <if test="name != null">
                NAME = #{name,jdbcType=VARCHAR},
            if>
            <if test="pwd != null">
                PWD = #{pwd,jdbcType=VARCHAR},
            if>
            <if test="createTime != null">
                CREATE_TIME = #{createTime,jdbcType=DATE},
            if>
            <if test="updateTime != null">
                UPDATE_TIME = #{updateTime,jdbcType=DATE},
            if>
        set>
        where ID = #{id,jdbcType=VARCHAR}
    
    id="updateByPrimaryKey" parameterType="sy.model.User">
        update tuser
        set CREATEDATETIME = #{createdatetime,jdbcType=TIMESTAMP},
        MODIFYDATETIME = #{modifydatetime,jdbcType=TIMESTAMP},
        NAME = #{name,jdbcType=VARCHAR},
        PWD = #{pwd,jdbcType=VARCHAR},
        CREATE_TIME = #{createTime,jdbcType=DATE},
        UPDATE_TIME = #{updateTime,jdbcType=DATE}
        where ID = #{id,jdbcType=VARCHAR}
    


    
    "sy.model.User" id="userResultMap" extends="BaseResultMap">
        property="userRoles" column="ID" javaType="list" select="selectUserRole" />
    
    

    "sy.model.User" id="userResultMap2" extends="BaseResultMap">
        property="userRoles" javaType="list" ofType="sy.model.UserRole">
            <id property="id" column="userrole_id" />
            <result column="role_id" property="roleId" />
            <result property="userId" column="user_id" />
        
    
    


    "sy.model.User" id="userResultMap3" extends="BaseResultMap">
        property="userRoles" javaType="list" ofType="sy.model.UserRole">
            <id property="id" column="userrole_id" />
            <result column="role_id" property="roleId" />
            <result property="userId" column="user_id" />
            property="role" javaType="sy.model.Role">
                <id property="id" column="role_id" />
                <result property="text" column="role_text" />
            
        
    
    

User.java

package sy.model;

import java.util.Date;
import java.util.List;

public class User {
    private List userRoles;

    private String id;

    private Date createdatetime;

    private Date modifydatetime;

    private String name;

    private String pwd;

    private Date createTime;

    private Date updateTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public Date getCreatedatetime() {
        return createdatetime;
    }

    public void setCreatedatetime(Date createdatetime) {
        this.createdatetime = createdatetime;
    }

    public Date getModifydatetime() {
        return modifydatetime;
    }

    public void setModifydatetime(Date modifydatetime) {
        this.modifydatetime = modifydatetime;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd == null ? null : pwd.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public List getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(List userRoles) {
        this.userRoles = userRoles;
    }
}

Role.java

package sy.model;

public class Role {
    private String id;

    private String text;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text == null ? null : text.trim();
    }
}

UserRole.java

package sy.model;

public class UserRole {
    private Role role;

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    private String id;

    private String roleId;

    private String userId;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public String getRoleId() {
        return roleId;
    }

    public void setRoleId(String roleId) {
        this.roleId = roleId == null ? null : roleId.trim();
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }
}

UserServiceI.java

package sy.service;

import java.util.List;

import sy.model.User;

public interface UserServiceI {

    public User getUserById(String id);

    List getAll();

    List getAll2();

    List getAll3();

}

UserServiceImpl.java

package sy.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sy.dao.UserMapper;
import sy.model.User;

@Service("userService")
public class UserServiceImpl implements UserServiceI {

    private UserMapper userMapper;

    public UserMapper getUserMapper() {
        return userMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User getUserById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List getAll() {
        return userMapper.getAll();
    }

    @Override
    public List getAll2() {
        return userMapper.getAll2();
    }

    @Override
    public List getAll3() {
        return userMapper.getAll3();
    }

}

TestMybatis.java (使用junit)
package sy.test;

import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import sy.model.User;
import sy.service.UserServiceI;

import com.alibaba.fastjson.JSON;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { “classpath:spring.xml”, “classpath:spring-mybatis.xml” })
public class TestMybatis {

private static final Logger logger = Logger.getLogger(TestMybatis.class);

private UserServiceI userService;

public UserServiceI getUserService() {
    return userService;
}

@Autowired
public void setUserService(UserServiceI userService) {
    this.userService = userService;
}

@Test
public void test1() {
    User u = userService.getUserById("1");
    logger.info(JSON.toJSONStringWithDateFormat(u, "yyyy-MM-dd HH:mm:ss"));
}

@Test
public void test2() {
    List l = userService.getAll();
    logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}

@Test
public void test3() {
    List l = userService.getAll2();
    logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}

@Test
public void test4() {
    List l = userService.getAll3();
    logger.info(JSON.toJSONStringWithDateFormat(l, "yyyy-MM-dd HH:mm:ss"));
}

}

你可能感兴趣的:(Spring + SpringMVC + mybatis + maven + junit)