SSM 项目搭建 (IDEA)

好好想了想,还是准备给大家发一个简单的SSM的项目搭建教程。

我觉得通常来说,只是XML的配置文件可能让人头痛了点,其他的倒真不是问题。

不过话说回来,mybatis一直让我觉得用起来不方便。因为数据库只要修改了字段,那么mapper.xml中的所有sql语句基本都要改。

这是多吓人的工作量啊。。。(大家别说数据库定下来就不太会改变。前期随着需求的改变,数据库相应变化必不可少。我又不是DDD模式。)


废话说了这么多,开始教程了

我使用的IDEA作为IDE


一 创建 Maven Project

记得是 Maven Project



groupId : testSSM

artifactId: testSSM




二 配置Pom.xml


  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <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">  
  4.   
  5.   <modelVersion>4.0.0</modelVersion>  
  6.   <packaging>war</packaging>  
  7.   
  8.   <name>testSSM</name>  
  9.   <groupId>testSSM</groupId>  
  10.   <artifactId>testSSM</artifactId>  
  11.   <version>1.0-SNAPSHOT</version>  
  12.   
  13.   <build>  
  14.     <plugins>  
  15.       <plugin>  
  16.         <groupId>org.mortbay.jetty</groupId>  
  17.         <artifactId>maven-jetty-plugin</artifactId>  
  18.         <version>6.1.7</version>  
  19.         <configuration>  
  20.           <connectors>  
  21.             <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">  
  22.               <port>8888</port>  
  23.               <maxIdleTime>30000</maxIdleTime>  
  24.             </connector>  
  25.           </connectors>  
  26.           <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>  
  27.           <contextPath>/</contextPath>  
  28.         </configuration>  
  29.       </plugin>  
  30.     </plugins>  
  31.   </build>  
  32.   
  33.   <properties>  
  34.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  35.     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  36.   
  37.     <!-- spring版本号 -->  
  38.     <spring.version>4.2.5.RELEASE</spring.version>  
  39.   
  40.     <!-- mybatis版本号 -->  
  41.     <mybatis.version>3.2.8</mybatis.version>  
  42.   
  43.     <!-- mysql驱动版本号 -->  
  44.     <mysql-driver.version>5.1.29</mysql-driver.version>  
  45.   
  46.     <!-- log4j日志包版本号 -->  
  47.     <slf4j.version>1.7.18</slf4j.version>  
  48.     <log4j.version>1.2.17</log4j.version>  
  49.   
  50.   </properties>  
  51.   
  52.   
  53.   <dependencies>  
  54.     <!-- 添加jstl依赖 -->  
  55.     <dependency>  
  56.       <groupId>jstl</groupId>  
  57.       <artifactId>jstl</artifactId>  
  58.       <version>1.2</version>  
  59.     </dependency>  
  60.   
  61.     <dependency>  
  62.       <groupId>javax</groupId>  
  63.       <artifactId>javaee-api</artifactId>  
  64.       <version>7.0</version>  
  65.     </dependency>  
  66.     <dependency>  
  67.       <groupId>com.alibaba</groupId>  
  68.       <artifactId>druid</artifactId>  
  69.       <version>1.0.16</version>  
  70.     </dependency>  
  71.     <!-- 添加junit4依赖 -->  
  72.     <dependency>  
  73.       <groupId>junit</groupId>  
  74.       <artifactId>junit</artifactId>  
  75.       <version>4.11</version>  
  76.       <!-- 指定范围,在测试时才会加载 -->  
  77.       <scope>test</scope>  
  78.     </dependency>  
  79.   
  80.     <!-- 添加spring核心依赖 -->  
  81.     <dependency>  
  82.       <groupId>org.springframework</groupId>  
  83.       <artifactId>spring-core</artifactId>  
  84.       <version>${spring.version}</version>  
  85.     </dependency>  
  86.     <dependency>  
  87.       <groupId>org.springframework</groupId>  
  88.       <artifactId>spring-web</artifactId>  
  89.       <version>${spring.version}</version>  
  90.     </dependency>  
  91.     <dependency>  
  92.       <groupId>org.springframework</groupId>  
  93.       <artifactId>spring-oxm</artifactId>  
  94.       <version>${spring.version}</version>  
  95.     </dependency>  
  96.     <dependency>  
  97.       <groupId>org.springframework</groupId>  
  98.       <artifactId>spring-tx</artifactId>  
  99.       <version>${spring.version}</version>  
  100.     </dependency>  
  101.     <dependency>  
  102.       <groupId>org.springframework</groupId>  
  103.       <artifactId>spring-jdbc</artifactId>  
  104.       <version>${spring.version}</version>  
  105.     </dependency>  
  106.     <dependency>  
  107.       <groupId>org.springframework</groupId>  
  108.       <artifactId>spring-webmvc</artifactId>  
  109.       <version>${spring.version}</version>  
  110.     </dependency>  
  111.     <dependency>  
  112.       <groupId>org.springframework</groupId>  
  113.       <artifactId>spring-context</artifactId>  
  114.       <version>${spring.version}</version>  
  115.     </dependency>  
  116.     <dependency>  
  117.       <groupId>org.springframework</groupId>  
  118.       <artifactId>spring-context-support</artifactId>  
  119.       <version>${spring.version}</version>  
  120.     </dependency>  
  121.     <dependency>  
  122.       <groupId>org.springframework</groupId>  
  123.       <artifactId>spring-aop</artifactId>  
  124.       <version>${spring.version}</version>  
  125.     </dependency>  
  126.   
  127.     <dependency>  
  128.       <groupId>org.springframework</groupId>  
  129.       <artifactId>spring-test</artifactId>  
  130.       <version>${spring.version}</version>  
  131.     </dependency>  
  132.   
  133.     <!-- 添加mybatis依赖 -->  
  134.     <dependency>  
  135.       <groupId>org.mybatis</groupId>  
  136.       <artifactId>mybatis</artifactId>  
  137.       <version>${mybatis.version}</version>  
  138.     </dependency>  
  139.   
  140.     <!-- 添加mybatis/spring整合包依赖 -->  
  141.     <dependency>  
  142.       <groupId>org.mybatis</groupId>  
  143.       <artifactId>mybatis-spring</artifactId>  
  144.       <version>1.2.2</version>  
  145.     </dependency>  
  146.   
  147.     <!-- 添加mysql驱动依赖 -->  
  148.     <dependency>  
  149.       <groupId>mysql</groupId>  
  150.       <artifactId>mysql-connector-java</artifactId>  
  151.       <version>${mysql-driver.version}</version>  
  152.     </dependency>  
  153.     <!-- 添加数据库连接池依赖 -->  
  154.     <dependency>  
  155.       <groupId>commons-dbcp</groupId>  
  156.       <artifactId>commons-dbcp</artifactId>  
  157.       <version>1.2.2</version>  
  158.     </dependency>  
  159.   
  160.     <!-- 添加fastjson -->  
  161.     <dependency>  
  162.       <groupId>com.alibaba</groupId>  
  163.       <artifactId>fastjson</artifactId>  
  164.       <version>1.1.41</version>  
  165.     </dependency>  
  166.   
  167.     <!-- 添加日志相关jar包 -->  
  168.     <dependency>  
  169.       <groupId>log4j</groupId>  
  170.       <artifactId>log4j</artifactId>  
  171.       <version>${log4j.version}</version>  
  172.     </dependency>  
  173.     <dependency>  
  174.       <groupId>org.slf4j</groupId>  
  175.       <artifactId>slf4j-api</artifactId>  
  176.       <version>${slf4j.version}</version>  
  177.     </dependency>  
  178.     <dependency>  
  179.       <groupId>org.slf4j</groupId>  
  180.       <artifactId>slf4j-log4j12</artifactId>  
  181.       <version>${slf4j.version}</version>  
  182.     </dependency>  
  183.   
  184.     <!-- log end -->  
  185.     <!-- 映入JSON -->  
  186.     <dependency>  
  187.       <groupId>org.codehaus.jackson</groupId>  
  188.       <artifactId>jackson-mapper-asl</artifactId>  
  189.       <version>1.9.13</version>  
  190.     </dependency>  
  191.     <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->  
  192.     <dependency>  
  193.       <groupId>com.fasterxml.jackson.core</groupId>  
  194.       <artifactId>jackson-core</artifactId>  
  195.       <version>2.8.0</version>  
  196.     </dependency>  
  197.     <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->  
  198.     <dependency>  
  199.       <groupId>com.fasterxml.jackson.core</groupId>  
  200.       <artifactId>jackson-databind</artifactId>  
  201.       <version>2.8.0</version>  
  202.     </dependency>  
  203.   
  204.     <dependency>  
  205.       <groupId>commons-fileupload</groupId>  
  206.       <artifactId>commons-fileupload</artifactId>  
  207.       <version>1.3.1</version>  
  208.     </dependency>  
  209.   
  210.     <dependency>  
  211.       <groupId>commons-io</groupId>  
  212.       <artifactId>commons-io</artifactId>  
  213.       <version>2.4</version>  
  214.     </dependency>  
  215.   
  216.     <dependency>  
  217.       <groupId>commons-codec</groupId>  
  218.       <artifactId>commons-codec</artifactId>  
  219.       <version>1.9</version>  
  220.     </dependency>  
  221.   </dependencies>  
  222.   
  223. </project>  
<?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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>testSSM</name>
  <groupId>testSSM</groupId>
  <artifactId>testSSM</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.7</version>
        <configuration>
          <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
              <port>8888</port>
              <maxIdleTime>30000</maxIdleTime>
            </connector>
          </connectors>
          <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory>
          <contextPath>/</contextPath>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!-- spring版本号 -->
    <spring.version>4.2.5.RELEASE</spring.version>

    <!-- mybatis版本号 -->
    <mybatis.version>3.2.8</mybatis.version>

    <!-- mysql驱动版本号 -->
    <mysql-driver.version>5.1.29</mysql-driver.version>

    <!-- log4j日志包版本号 -->
    <slf4j.version>1.7.18</slf4j.version>
    <log4j.version>1.2.17</log4j.version>

  </properties>


  <dependencies>
    <!-- 添加jstl依赖 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.16</version>
    </dependency>
    <!-- 添加junit4依赖 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <!-- 指定范围,在测试时才会加载 -->
      <scope>test</scope>
    </dependency>

    <!-- 添加spring核心依赖 -->
    <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-context</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-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- 添加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>

    <!-- 添加mysql驱动依赖 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql-driver.version}</version>
    </dependency>
    <!-- 添加数据库连接池依赖 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- 添加fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.41</version>
    </dependency>

    <!-- 添加日志相关jar包 -->
    <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>

    <!-- log end -->
    <!-- 映入JSON -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.0</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>

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
  </dependencies>

</project>


三  创建数据库

创建表
  1. CREATE TABLE `tb_user` (  
  2.   `UserID` int(11) NOT NULL AUTO_INCREMENT,  
  3.   `UserName` varchar(255) DEFAULT NULL,  
  4.   `RealName` varchar(255) DEFAULT NULL,  
  5.   `Passwordvarchar(255) DEFAULT NULL,  
  6.   `IsLock` int(11) DEFAULT NULL,  
  7.   `CreateTime` datetime DEFAULT CURRENT_TIMESTAMP,  
  8.   PRIMARY KEY (`UserID`),  
  9.   UNIQUE KEY `id` (`UserName`)  
  10. ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;  
CREATE TABLE `tb_user` (
  `UserID` int(11) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(255) DEFAULT NULL,
  `RealName` varchar(255) DEFAULT NULL,
  `Password` varchar(255) DEFAULT NULL,
  `IsLock` int(11) DEFAULT NULL,
  `CreateTime` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`UserID`),
  UNIQUE KEY `id` (`UserName`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;



新增数据



四 搭建SSM分层结构





注意,创建完上面5个包后,需要进行如下操作


选择java,然后点击Sources,java文件夹会变蓝。

同样,选择resources,然后点击 Resources, resources会出现黄色横杠。



五 添加xml配置文件

先看一下配置文件


1 web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
  5.           http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  6.          version="3.0">  
  7.   
  8.   <display-name>testSSM</display-name>  
  9.   
  10.   <context-param>  
  11.     <param-name>contextConfigLocation</param-name>  
  12.     <param-value>classpath:spring-mybatis.xml</param-value>  
  13.   </context-param>  
  14.   
  15.   <context-param>  
  16.     <param-name>log4jConfigLocation</param-name>  
  17.     <param-value>classpath:log4j.properties</param-value>  
  18.   </context-param>  
  19.   
  20.   <!-- 编码过滤器 -->  
  21.   <filter>  
  22.     <filter-name>encodingFilter</filter-name>  
  23.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  24.     <init-param>  
  25.       <param-name>encoding</param-name>  
  26.       <param-value>UTF-8</param-value>  
  27.     </init-param>  
  28.   </filter>  
  29.   <filter-mapping>  
  30.     <filter-name>encodingFilter</filter-name>  
  31.     <url-pattern>/*</url-pattern>  
  32.   </filter-mapping>  
  33.   
  34.   <!-- spring监听器 -->  
  35.   <listener>  
  36.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  37.   </listener>  
  38.   
  39.   <!-- 防止spring内存溢出监听器,比如quartz -->  
  40.   <listener>  
  41.     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  42.   </listener>  
  43.   
  44.   
  45.   <!-- spring mvc servlet-->  
  46.   <servlet>  
  47.     <servlet-name>testSSM</servlet-name>  
  48.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  49.     <init-param>  
  50.       <param-name>contextConfigLocation</param-name>  
  51.       <param-value>classpath:spring-mvc.xml</param-value>  
  52.     </init-param>  
  53.     <load-on-startup>1</load-on-startup>  
  54.     <async-supported>true</async-supported>  
  55.   </servlet>  
  56.   <servlet-mapping>  
  57.     <servlet-name>testSSM</servlet-name>  
  58.     <!-- 此处也可以配置成 *.do 形式 -->  
  59.     <url-pattern>/</url-pattern>  
  60.   </servlet-mapping>  
  61.   
  62.   <welcome-file-list>  
  63.     <welcome-file>/index.jsp</welcome-file>  
  64.   </welcome-file-list>  
  65.   
  66.   <!-- session配置 -->  
  67.   <session-config>  
  68.     <session-timeout>15</session-timeout>  
  69.   </session-config>  
  70.   
  71. </web-app>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         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>testSSM</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>

  <!-- 编码过滤器 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 防止spring内存溢出监听器,比如quartz -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>


  <!-- spring mvc servlet-->
  <servlet>
    <servlet-name>testSSM</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>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>testSSM</servlet-name>
    <!-- 此处也可以配置成 *.do 形式 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>

  <!-- session配置 -->
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

</web-app>


2 jdbc.properties

  1. #driverClasss=com.mysql.jdbc.Driver  
  2. jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx:3306/testdb  
  3. #?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&autoReconnectForPools=true&noAccessToProcedureBodies=true  
  4. username=root  
  5. password=root  
  6.   
  7. #定义初始连接数  
  8. initialSize=0    
  9. #定义最大连接数  
  10. maxActive=20    
  11. #定义最大空闲  
  12. maxIdle=20    
  13. #定义最小空闲  
  14. minIdle=1    
  15. #定义最长等待时间  
  16. maxWait=60000    
#driverClasss=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://xxx.xxx.xxx.xxx:3306/testdb
#?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&autoReconnectForPools=true&noAccessToProcedureBodies=true
username=root
password=root

#定义初始连接数
initialSize=0  
#定义最大连接数
maxActive=20  
#定义最大空闲
maxIdle=20  
#定义最小空闲
minIdle=1  
#定义最长等待时间
maxWait=60000  


3 log4j.properties

  1. log4j.rootLogger=INFO,Console,File    
  2.   
  3. #控制台日志  
  4. log4j.appender.Console=org.apache.log4j.ConsoleAppender    
  5. log4j.appender.Console.Target=System.out    
  6. log4j.appender.Console.layout=org.apache.log4j.PatternLayout    
  7. log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n    
  8.   
  9. #普通文件日志  
  10. log4j.appender.File=org.apache.log4j.RollingFileAppender    
  11. log4j.appender.File.File=logs/ssm.log    
  12. log4j.appender.File.MaxFileSize=10MB    
  13. #输出日志,如果换成DEBUG表示输出DEBUG以上级别日志  
  14. log4j.appender.File.Threshold=ALL    
  15. log4j.appender.File.layout=org.apache.log4j.PatternLayout    
  16. log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n    
log4j.rootLogger=INFO,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][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n  

#普通文件日志
log4j.appender.File=org.apache.log4j.RollingFileAppender  
log4j.appender.File.File=logs/ssm.log  
log4j.appender.File.MaxFileSize=10MB  
#输出日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold=ALL  
log4j.appender.File.layout=org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n  


4 mybatisConfig.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  3. <configuration>  
  4.     <settings>  
  5.         <!-- <setting name="logImpl" value="LOG4J"/>   -->  
  6.         <!-- <setting name="cacheEnabled" value="true"/>  
  7.         <setting name="lazyLoadingEnabled" value="true"/>  
  8.         <setting name="multipleResultSetsEnabled" value="true"/>  
  9.         <setting name="useColumnLabel" value="true"/>  
  10.         <setting name="useGeneratedKeys" value="false"/>  
  11.         <setting name="defaultExecutorType" value="SIMPLE"/>  
  12.         <setting name="defaultStatementTimeout" value="25000"/> -->  
  13.         <setting name="logImpl" value="SLF4J"/>  
  14.         <setting name="callSettersOnNulls" value="true"/>  
  15.         <!--<setting name="autoMappingBehavior" value="true"/>-->  
  16.     </settings>  
  17.   
  18. </configuration>  
<?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="logImpl" value="LOG4J"/>   -->
        <!-- <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25000"/> -->
        <setting name="logImpl" value="SLF4J"/>
        <setting name="callSettersOnNulls" value="true"/>
        <!--<setting name="autoMappingBehavior" value="true"/>-->
    </settings>

</configuration>


5 spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.                         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  8.                         http://www.springframework.org/schema/context  
  9.                         http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  10.                         http://www.springframework.org/schema/mvc  
  11.                         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
  12.   
  13.     <!-- 自动扫描  @Controller-->  
  14.     <context:component-scan base-package="controller"/>  
  15.   
  16.     <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  
  17.     <bean id="mappingJacksonHttpMessageConverter"  
  18.           class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
  19.         <property name="supportedMediaTypes">  
  20.             <list>  
  21.                 <value>text/html;charset=UTF-8</value>  
  22.             </list>  
  23.         </property>  
  24.     </bean>  
  25.     <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->  
  26.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  27.         <property name="messageConverters">  
  28.             <list>  
  29.                 <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 -->  
  30.             </list>  
  31.         </property>  
  32.     </bean>  
  33.   
  34.   
  35.     <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->  
  36.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  37.         <property name="prefix" value="/WEB-INF/" />  
  38.         <property name="suffix" value=".jsp"/>  
  39.     </bean>  
  40.   
  41.     <!-- 文件上传配置 -->  
  42.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  43.         <!-- 默认编码 -->  
  44.         <property name="defaultEncoding" value="UTF-8"/>  
  45.         <!-- 上传文件大小限制为31M,31*1024*1024 -->  
  46.         <property name="maxUploadSize" value="32505856"/>  
  47.         <!-- 内存中的最大值 -->  
  48.         <property name="maxInMemorySize" value="4096"/>  
  49.     </bean>  
  50. </beans>  
<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       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.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 自动扫描  @Controller-->
    <context:component-scan base-package="controller"/>

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>


    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="4096"/>
    </bean>
</beans>


6 spring-mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.                         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  7.                         http://www.springframework.org/schema/context  
  8.                         http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  9.                         http://www.springframework.org/schema/tx  
  10.                         http://www.springframework.org/schema/tx/spring-tx.xsd">  
  11.   
  12.     <!-- 自动扫描 -->  
  13.     <context:component-scan base-package="controller"/>  
  14.   
  15.     <!-- 第一种方式:加载一个properties文件 -->  
  16.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  17.         <property name="location" value="classpath:jdbc.properties"/>  
  18.     </bean>  
  19.   
  20.   
  21.     <!-- 第二种方式:加载多个properties文件  
  22.     <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  23.         <property name="locations">  
  24.             <list>  
  25.                 <value>classpath:jdbc.properties</value>  
  26.                 <value>classpath:common.properties</value>  
  27.             </list>  
  28.         </property>  
  29.         <property name="fileEncoding" value="UTF-8"/>  
  30.     </bean>  
  31.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
  32.         <property name="properties" ref="configProperties"/>  
  33.     </bean>  
  34.     -->  
  35.   
  36.     <!-- 配置数据源 -->  
  37.     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  
  38.           destroy-method="close">  
  39.         <!--<property name="driverClassName" value="${driverClasss}"/>-->  
  40.         <property name="url" value="${jdbcUrl}"/>  
  41.         <property name="username" value="${username}"/>  
  42.         <property name="password" value="${password}"/>  
  43.         <!-- 初始化连接大小 -->  
  44.         <property name="initialSize" value="${initialSize}"></property>  
  45.         <!-- 连接池最大数量 -->  
  46.         <property name="maxActive" value="${maxActive}"></property>  
  47.         <!-- 连接池最大空闲 -->  
  48.         <property name="maxIdle" value="${maxIdle}"></property>  
  49.         <!-- 连接池最小空闲 -->  
  50.         <property name="minIdle" value="${minIdle}"></property>  
  51.         <!-- 获取连接最大等待时间 -->  
  52.         <property name="maxWait" value="${maxWait}"></property>  
  53.     </bean>  
  54.   
  55.     <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->  
  56.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  57.         <property name="dataSource" ref="dataSource"/>  
  58.         <property name="configLocation">  
  59.             <value>classpath:mybatisConfig.xml</value>  
  60.         </property>  
  61.         <!-- 自动扫描mapping.xml文件 -->  
  62.         <property name="mapperLocations" value="classpath:mapping/*.xml"></property>  
  63.   
  64.     </bean>  
  65.   
  66.     <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
  67.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  68.         <property name="basePackage" value="dao"/>  
  69.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
  70.     </bean>  
  71.   
  72.   
  73.     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
  74.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  75.         <property name="dataSource" ref="dataSource"/>  
  76.     </bean>  
  77.   
  78.     <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
  79.     <tx:annotation-driven transaction-manager="transactionManager"/>  
  80. </beans>  
<?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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="controller"/>

    <!-- 第一种方式:加载一个properties文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>


    <!-- 第二种方式:加载多个properties文件
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:common.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="UTF-8"/>
    </bean>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties"/>
    </bean>
    -->

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <!--<property name="driverClassName" value="${driverClasss}"/>-->
        <property name="url" value="${jdbcUrl}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation">
            <value>classpath:mybatisConfig.xml</value>
        </property>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapping/*.xml"></property>

    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>


    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>



六 搭建功能和测试

1 UserMapper.xml (位于resources/mapping文件夹下)

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="dao.UserMapper" >  
  4.     <resultMap id="BaseResultMap" type="model.User" >  
  5.         <id column="UserID" property="userid" jdbcType="INTEGER" />  
  6.         <result column="UserName" property="username" jdbcType="VARCHAR" />  
  7.         <result column="RealName" property="realname" jdbcType="VARCHAR" />  
  8.         <result column="Password" property="password" jdbcType="VARCHAR" />  
  9.         <result column="IsLock" property="islock" jdbcType="INTEGER" />  
  10.         <result column="CreateTime" property="createtime" jdbcType="TIMESTAMP" />  
  11.     </resultMap>  
  12.     <sql id="Base_Column_List" >  
  13.         UserID, UserName, RealName, Password, IsLock, CreateTime  
  14.     </sql>  
  15.     <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >  
  16.         select  
  17.         <include refid="Base_Column_List" />  
  18.         from tb_user  
  19.         where UserID = #{userid,jdbcType=INTEGER}  
  20.     </select>  
  21.     <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >  
  22.         delete from tb_user  
  23.         where UserID = #{userid,jdbcType=INTEGER}  
  24.     </delete>  
  25.     <insert id="insert" parameterType="model.User" >  
  26.         insert into tb_user (UserID, UserName, RealName,  
  27.         Password, IsLock, CreateTime  
  28.         )  
  29.         values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{realname,jdbcType=VARCHAR},  
  30.         #{password,jdbcType=VARCHAR}, #{islock,jdbcType=INTEGER}, #{createtime,jdbcType=TIMESTAMP}  
  31.         )  
  32.     </insert>  
  33.     <insert id="insertSelective" parameterType="model.User" >  
  34.         insert into tb_user  
  35.         <trim prefix="(" suffix=")" suffixOverrides="," >  
  36.             <if test="userid != null" >  
  37.                 UserID,  
  38.             </if>  
  39.             <if test="username != null" >  
  40.                 UserName,  
  41.             </if>  
  42.             <if test="realname != null" >  
  43.                 RealName,  
  44.             </if>  
  45.             <if test="password != null" >  
  46.                 Password,  
  47.             </if>  
  48.             <if test="islock != null" >  
  49.                 IsLock,  
  50.             </if>  
  51.             <if test="createtime != null" >  
  52.                 CreateTime,  
  53.             </if>  
  54.         </trim>  
  55.         <trim prefix="values (" suffix=")" suffixOverrides="," >  
  56.             <if test="userid != null" >  
  57.                 #{userid,jdbcType=INTEGER},  
  58.             </if>  
  59.             <if test="username != null" >  
  60.                 #{username,jdbcType=VARCHAR},  
  61.             </if>  
  62.             <if test="realname != null" >  
  63.                 #{realname,jdbcType=VARCHAR},  
  64.             </if>  
  65.             <if test="password != null" >  
  66.                 #{password,jdbcType=VARCHAR},  
  67.             </if>  
  68.             <if test="islock != null" >  
  69.                 #{islock,jdbcType=INTEGER},  
  70.             </if>  
  71.             <if test="createtime != null" >  
  72.                 #{createtime,jdbcType=TIMESTAMP},  
  73.             </if>  
  74.         </trim>  
  75.     </insert>  
  76.     <update id="updateByPrimaryKeySelective" parameterType="model.User" >  
  77.         update tb_user  
  78.         <set >  
  79.             <if test="username != null" >  
  80.                 UserName = #{username,jdbcType=VARCHAR},  
  81.             </if>  
  82.             <if test="realname != null" >  
  83.                 RealName = #{realname,jdbcType=VARCHAR},  
  84.             </if>  
  85.             <if test="password != null" >  
  86.                 Password = #{password,jdbcType=VARCHAR},  
  87.             </if>  
  88.             <if test="islock != null" >  
  89.                 IsLock = #{islock,jdbcType=INTEGER},  
  90.             </if>  
  91.             <if test="createtime != null" >  
  92.                 CreateTime = #{createtime,jdbcType=TIMESTAMP},  
  93.             </if>  
  94.         </set>  
  95.         where UserID = #{userid,jdbcType=INTEGER}  
  96.     </update>  
  97.     <update id="updateByPrimaryKey" parameterType="model.User" >  
  98.         update tb_user  
  99.         set UserName = #{username,jdbcType=VARCHAR},  
  100.         RealName = #{realname,jdbcType=VARCHAR},  
  101.         Password = #{password,jdbcType=VARCHAR},  
  102.         IsLock = #{islock,jdbcType=INTEGER},  
  103.         CreateTime = #{createtime,jdbcType=TIMESTAMP}  
  104.         where UserID = #{userid,jdbcType=INTEGER}  
  105.     </update>  
  106. </mapper>  
<?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="dao.UserMapper" >
    <resultMap id="BaseResultMap" type="model.User" >
        <id column="UserID" property="userid" jdbcType="INTEGER" />
        <result column="UserName" property="username" jdbcType="VARCHAR" />
        <result column="RealName" property="realname" jdbcType="VARCHAR" />
        <result column="Password" property="password" jdbcType="VARCHAR" />
        <result column="IsLock" property="islock" jdbcType="INTEGER" />
        <result column="CreateTime" property="createtime" jdbcType="TIMESTAMP" />
    </resultMap>
    <sql id="Base_Column_List" >
        UserID, UserName, RealName, Password, IsLock, CreateTime
    </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from tb_user
        where UserID = #{userid,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from tb_user
        where UserID = #{userid,jdbcType=INTEGER}
    </delete>
    <insert id="insert" parameterType="model.User" >
        insert into tb_user (UserID, UserName, RealName,
        Password, IsLock, CreateTime
        )
        values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{realname,jdbcType=VARCHAR},
        #{password,jdbcType=VARCHAR}, #{islock,jdbcType=INTEGER}, #{createtime,jdbcType=TIMESTAMP}
        )
    </insert>
    <insert id="insertSelective" parameterType="model.User" >
        insert into tb_user
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="userid != null" >
                UserID,
            </if>
            <if test="username != null" >
                UserName,
            </if>
            <if test="realname != null" >
                RealName,
            </if>
            <if test="password != null" >
                Password,
            </if>
            <if test="islock != null" >
                IsLock,
            </if>
            <if test="createtime != null" >
                CreateTime,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="userid != null" >
                #{userid,jdbcType=INTEGER},
            </if>
            <if test="username != null" >
                #{username,jdbcType=VARCHAR},
            </if>
            <if test="realname != null" >
                #{realname,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="islock != null" >
                #{islock,jdbcType=INTEGER},
            </if>
            <if test="createtime != null" >
                #{createtime,jdbcType=TIMESTAMP},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="model.User" >
        update tb_user
        <set >
            <if test="username != null" >
                UserName = #{username,jdbcType=VARCHAR},
            </if>
            <if test="realname != null" >
                RealName = #{realname,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                Password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="islock != null" >
                IsLock = #{islock,jdbcType=INTEGER},
            </if>
            <if test="createtime != null" >
                CreateTime = #{createtime,jdbcType=TIMESTAMP},
            </if>
        </set>
        where UserID = #{userid,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="model.User" >
        update tb_user
        set UserName = #{username,jdbcType=VARCHAR},
        RealName = #{realname,jdbcType=VARCHAR},
        Password = #{password,jdbcType=VARCHAR},
        IsLock = #{islock,jdbcType=INTEGER},
        CreateTime = #{createtime,jdbcType=TIMESTAMP}
        where UserID = #{userid,jdbcType=INTEGER}
    </update>
</mapper>


2 User对象(model)

  1. package model;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.     private Integer userid;  
  7.   
  8.     private String username;  
  9.   
  10.     private String realname;  
  11.   
  12.     private String password;  
  13.   
  14.     private Integer islock;  
  15.   
  16.     private Date createtime;  
  17.   
  18.     public Integer getUserid() {  
  19.         return userid;  
  20.     }  
  21.   
  22.     public void setUserid(Integer userid) {  
  23.         this.userid = userid;  
  24.     }  
  25.   
  26.     public String getUsername() {  
  27.         return username;  
  28.     }  
  29.   
  30.     public void setUsername(String username) {  
  31.         this.username = username == null ? null : username.trim();  
  32.     }  
  33.   
  34.     public String getRealname() {  
  35.         return realname;  
  36.     }  
  37.   
  38.     public void setRealname(String realname) {  
  39.         this.realname = realname == null ? null : realname.trim();  
  40.     }  
  41.   
  42.     public String getPassword() {  
  43.         return password;  
  44.     }  
  45.   
  46.     public void setPassword(String password) {  
  47.         this.password = password == null ? null : password.trim();  
  48.     }  
  49.   
  50.     public Integer getIslock() {  
  51.         return islock;  
  52.     }  
  53.   
  54.     public void setIslock(Integer islock) {  
  55.         this.islock = islock;  
  56.     }  
  57.   
  58.     public Date getCreatetime() {  
  59.         return createtime;  
  60.     }  
  61.   
  62.     public void setCreatetime(Date createtime) {  
  63.         this.createtime = createtime;  
  64.     }  
  65. }  
package model;

import java.util.Date;

public class User {
    private Integer userid;

    private String username;

    private String realname;

    private String password;

    private Integer islock;

    private Date createtime;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname == null ? null : realname.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public Integer getIslock() {
        return islock;
    }

    public void setIslock(Integer islock) {
        this.islock = islock;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
}


3 dao

  1. package dao;  
  2.   
  3. import model.User;  
  4.   
  5. public interface UserMapper {  
  6.     int deleteByPrimaryKey(Integer userid);  
  7.   
  8.     int insert(User record);  
  9.   
  10.     int insertSelective(User record);  
  11.   
  12.     User selectByPrimaryKey(Integer userid);  
  13.   
  14.     int updateByPrimaryKeySelective(User record);  
  15.   
  16.     int updateByPrimaryKey(User record);  
  17. }  
package dao;

import model.User;

public interface UserMapper {
    int deleteByPrimaryKey(Integer userid);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userid);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}


4 controller

(由于是测试,就不在创建 service和impl层了。直接调用通过就可以了。)

  1. package controller;  
  2.   
  3. import dao.UserMapper;  
  4. import model.User;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.ModelMap;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.servlet.ModelAndView;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13. import java.util.List;  
  14.   
  15. /** 
  16.  * Created by Tyler on 2017/6/20. 
  17.  */  
  18.   
  19. @Controller  
  20. @RequestMapping("test")  
  21. public class TestController {  
  22.   
  23.     @Autowired  
  24.     protected UserMapper service;  
  25.   
  26.     @RequestMapping(value = "test.do")  
  27.     public ModelAndView test1(HttpServletRequest request, HttpServletResponse response, ModelMap mode) throws Exception {  
  28.         User u =service.selectByPrimaryKey(1);  
  29.   
  30.         return new ModelAndView("test/test");  
  31.     }  
  32. }  
package controller;

import dao.UserMapper;
import model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Tyler on 2017/6/20.
 */

@Controller
@RequestMapping("test")
public class TestController {

    @Autowired
    protected UserMapper service;

    @RequestMapping(value = "test.do")
    public ModelAndView test1(HttpServletRequest request, HttpServletResponse response, ModelMap mode) throws Exception {
        User u =service.selectByPrimaryKey(1);

        return new ModelAndView("test/test");
    }
}


PS: protected UserMapper service; 如果这句报错,可以无视。运行没关系。

5 创建 page

webapp  -->  test  -->  test.jsp


最后运行一下页面就可以了。
http://localhost:8080/testssm/test/test.do

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值