常用框架(一):spring+springMvc+mybatis+maven

项目说明:

(1) 本例采用 maven web 工程做例子讲解

(2) 利用mybaits 提供的代码生成工具自动生成代码(dao接口,sql mapper映射文件,pojo数据库映射类)

(3) 数据库用 mysql

项目构建:

一,新建maven web 工程

网上有很多详细的教程,初学者可以点这里跳转学习:eclipse创建maven工程

本例项目结构如下,待会再一步一步讲解:


二,引入需要的jar包到pom.xml中,配置如下:

[html]  view plain  copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.maven.web</groupId>  
  5.     <artifactId>com.maven.web</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>com.maven.web Maven Webapp</name>  
  9.   
  10.     <properties>  
  11.         <spring.version>4.3.0.RELEASE</spring.version>  
  12.         <jackson.version>2.6.5</jackson.version>  
  13.         <fastjson.version>1.2.23</fastjson.version>  
  14.         <mybatis.version>3.3.0</mybatis.version>  
  15.         <mybatis-spring.version>1.2.3</mybatis-spring.version>  
  16.         <mysql.connector.version>5.1.29</mysql.connector.version>  
  17.     </properties>  
  18.   
  19.     <repositories>  
  20.         <repository>  
  21.             <id>spring-milestones</id>  
  22.             <name>Spring Milestones</name>  
  23.             <url>https://repo.spring.io/libs-milestone</url>  
  24.             <snapshots>  
  25.                 <enabled>false</enabled>  
  26.             </snapshots>  
  27.         </repository>  
  28.     </repositories>  
  29.   
  30.     <dependencies>  
  31.         <dependency>  
  32.             <groupId>junit</groupId>  
  33.             <artifactId>junit</artifactId>  
  34.             <version>3.8.1</version>  
  35.             <scope>test</scope>  
  36.         </dependency>  
  37.   
  38.         <dependency>  
  39.             <groupId>javax.annotation</groupId>  
  40.             <artifactId>javax.annotation-api</artifactId>  
  41.             <version>1.2</version>  
  42.         </dependency>  
  43.   
  44.         <!-- Spring -->  
  45.         <dependency>  
  46.             <groupId>org.springframework</groupId>  
  47.             <artifactId>spring-core</artifactId>  
  48.             <version>${spring.version}</version>  
  49.         </dependency>  
  50.         <dependency>  
  51.             <groupId>org.springframework</groupId>  
  52.             <artifactId>spring-expression</artifactId>  
  53.             <version>${spring.version}</version>  
  54.         </dependency>  
  55.         <dependency>  
  56.             <groupId>org.springframework</groupId>  
  57.             <artifactId>spring-beans</artifactId>  
  58.             <version>${spring.version}</version>  
  59.         </dependency>  
  60.         <dependency>  
  61.             <groupId>org.springframework</groupId>  
  62.             <artifactId>spring-aop</artifactId>  
  63.             <version>${spring.version}</version>  
  64.         </dependency>  
  65.         <dependency>  
  66.             <groupId>org.springframework</groupId>  
  67.             <artifactId>spring-context</artifactId>  
  68.             <version>${spring.version}</version>  
  69.         </dependency>  
  70.         <dependency>  
  71.             <groupId>org.springframework</groupId>  
  72.             <artifactId>spring-context-support</artifactId>  
  73.             <version>${spring.version}</version>  
  74.         </dependency>  
  75.         <dependency>  
  76.             <groupId>org.springframework</groupId>  
  77.             <artifactId>spring-orm</artifactId>  
  78.             <version>${spring.version}</version>  
  79.         </dependency>  
  80.         <dependency>  
  81.             <groupId>org.springframework</groupId>  
  82.             <artifactId>spring-oxm</artifactId>  
  83.             <version>${spring.version}</version>  
  84.         </dependency>  
  85.         <dependency>  
  86.             <groupId>org.springframework</groupId>  
  87.             <artifactId>spring-tx</artifactId>  
  88.             <version>${spring.version}</version>  
  89.         </dependency>  
  90.         <dependency>  
  91.             <groupId>org.springframework</groupId>  
  92.             <artifactId>spring-web</artifactId>  
  93.             <version>${spring.version}</version>  
  94.         </dependency>  
  95.         <dependency>  
  96.             <groupId>org.springframework</groupId>  
  97.             <artifactId>spring-webmvc</artifactId>  
  98.             <version>${spring.version}</version>  
  99.         </dependency>  
  100.   
  101.         <dependency>  
  102.             <groupId>commons-dbcp</groupId>  
  103.             <artifactId>commons-dbcp</artifactId>  
  104.             <version>1.4</version>  
  105.         </dependency>  
  106.   
  107.         <!-- mybatis start -->  
  108.         <dependency>  
  109.             <groupId>org.mybatis</groupId>  
  110.             <artifactId>mybatis</artifactId>  
  111.             <version>${mybatis.version}</version>  
  112.         </dependency>  
  113.         <dependency>  
  114.             <groupId>org.mybatis</groupId>  
  115.             <artifactId>mybatis-spring</artifactId>  
  116.             <version>${mybatis-spring.version}</version>  
  117.         </dependency>  
  118.         <dependency>  
  119.             <groupId>org.mybatis</groupId>  
  120.             <artifactId>mybatis-generator-core</artifactId>  
  121.             <version>1.3.2</version>  
  122.         </dependency>  
  123.         <dependency>  
  124.             <groupId>mysql</groupId>  
  125.             <artifactId>mysql-connector-java</artifactId>  
  126.             <version>${mysql.connector.version}</version>  
  127.         </dependency>  
  128.   
  129.         <dependency>  
  130.             <groupId>org.apache.commons</groupId>  
  131.             <artifactId>commons-lang3</artifactId>  
  132.             <version>3.4</version>  
  133.         </dependency>  
  134.   
  135.         <!-- jackson -->  
  136.         <dependency>  
  137.             <groupId>com.fasterxml.jackson.core</groupId>  
  138.             <artifactId>jackson-core</artifactId>  
  139.             <version>${jackson.version}</version>  
  140.         </dependency>  
  141.         <dependency>  
  142.             <groupId>com.fasterxml.jackson.core</groupId>  
  143.             <artifactId>jackson-databind</artifactId>  
  144.             <version>${jackson.version}</version>  
  145.         </dependency>  
  146.         <dependency>  
  147.             <groupId>com.fasterxml.jackson.core</groupId>  
  148.             <artifactId>jackson-annotations</artifactId>  
  149.             <version>${jackson.version}</version>  
  150.         </dependency>  
  151.   
  152.         <!-- fastjson -->  
  153.         <dependency>  
  154.             <groupId>com.alibaba</groupId>  
  155.             <artifactId>fastjson</artifactId>  
  156.             <version>${fastjson.version}</version>  
  157.         </dependency>  
  158.         <!-- fastjson -->  
  159.   
  160.         <dependency>  
  161.             <groupId>javax.servlet</groupId>  
  162.             <artifactId>javax.servlet-api</artifactId>  
  163.             <version>3.1.0</version>  
  164.             <scope>provided</scope>  
  165.         </dependency>  
  166.   
  167.     </dependencies>  
  168.   
  169.     <build>  
  170.         <finalName>com.maven.web</finalName>  
  171.     </build>  
  172.   
  173.   
  174. </project>  

=== 这里需要注意的是,mybaits自动生成代码的工具包我是放在本地的,项目源码会在文末分享。

找到lib包下面的mybatis-generator-core-1.3.2.jar,按照pom.xml中配置的路径放到自己本地即可。

同时需要在同目录下新建mybatis-generator-core-1.3.2.pom,然后加入以下配置内容。

[html]  view plain  copy
  1. <dependency>  
  2.     <groupId>org.mybatis</groupId>  
  3.     <artifactId>mybatis-generator-core</artifactId>  
  4.     <version>1.3.2</version>  
  5. </dependency>  
三,配置web.xml,加入spring + springMvc 核心监听器,配置如下:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     version="3.0">  
  6.   
  7.     <!-- 设置Spring容器加载所有的配置文件的路径 -->   
  8.     <context-param>  
  9.         <param-name>contextConfigLocation</param-name>  
  10.         <param-value>classpath:Spring-config.xml</param-value>  
  11.     </context-param>  
  12.       
  13.     <!-- 加载Spring容器配置 -->    
  14.     <listener>    
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    
  16.     </listener>    
  17.     
  18.     <!-- 防止Spring内存溢出监听器 -->    
  19.     <listener>    
  20.         <listener-class> org.springframework.web.context.ContextCleanupListener</listener-class>    
  21.     </listener>  
  22.       
  23.     <!-- 字符编码过滤器  -->  
  24.     <filter>  
  25.         <filter-name>encodingFilter</filter-name>  
  26.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  27.         <async-supported>true</async-supported>  
  28.         <init-param>  
  29.             <param-name>encoding</param-name>  
  30.             <param-value>UTF-8</param-value>  
  31.         </init-param>  
  32.         <init-param>  
  33.             <param-name>forceEncoding</param-name>  
  34.             <param-value>true</param-value>  
  35.         </init-param>  
  36.     </filter>  
  37.     <filter-mapping>  
  38.         <filter-name>encodingFilter</filter-name>  
  39.         <url-pattern>/*</url-pattern>  
  40.     </filter-mapping>  
  41.   
  42.     <!-- 配置SpringMVC核心控制器 -->  
  43.     <servlet>  
  44.         <servlet-name>SpringMVC</servlet-name>  
  45.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  46.         <init-param>  
  47.             <param-name>contextConfigLocation</param-name>  
  48.             <param-value>classpath:Spring-servlet.xml</param-value>  
  49.         </init-param>  
  50.         <load-on-startup>1</load-on-startup>  
  51.         <async-supported>true</async-supported>  
  52.     </servlet>  
  53.     <servlet-mapping>  
  54.         <servlet-name>SpringMVC</servlet-name>  
  55.         <url-pattern>/</url-pattern>  
  56.     </servlet-mapping>  
  57.       
  58.     <!-- session超时设置 -->  
  59.     <session-config>  
  60.         <session-timeout>30</session-timeout>  
  61.     </session-config>  
  62.       
  63.     <!-- 项目启动首页 -->  
  64.     <welcome-file-list>  
  65.         <welcome-file>index.jsp</welcome-file>  
  66.     </welcome-file-list>  
  67. </web-app>  
大家可以看到,在web.xml中加入了两个配置文件:

classpath:Spring-config.xml :这个是Spring的核心配置文件,用于管理bean,集成其他框架等等

classpath:Spring-servlet.xml:这个是SpringMvc的核心配置文件


四,Spring-config.xml ,,与mybatis集成,配置如下:

[html]  view plain  copy
  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"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  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/tx   
  11.           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
  12.             
  13.     <!-- 扫描注解 -->  
  14.     <context:component-scan base-package="com.maven.web">  
  15.         <context:exclude-filter type="annotation"  
  16.             expression="org.springframework.stereotype.Controller" />  
  17.     </context:component-scan>  
  18.   
  19.     <!-- 1. 数据源 : DriverManagerDataSource -->  
  20.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
  21.         destroy-method="close">  
  22.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  23.         <property name="url" value="jdbc:mysql://127.0.0.1:3306/yun?characterEncoding=utf8" />  
  24.         <property name="username" value="root" />  
  25.         <property name="password" value="centos" />  
  26.         <!-- 从池中获取连接前进行验证 -->  
  27.         <property name="testOnBorrow" value="false" />  
  28.         <!-- 向池中还回连接前进行验证 -->  
  29.         <property name="testOnReturn" value="false" />  
  30.         <!-- 连接空闲时验证 -->  
  31.         <property name="testWhileIdle" value="true" />  
  32.         <!-- 运行判断连接超时任务(evictor)的时间间隔,单位为毫秒,默认为-1,即不执行任务。 -->  
  33.         <property name="timeBetweenEvictionRunsMillis" value="300000" />  
  34.         <!-- 连接的超时时间,默认为半小时。 -->  
  35.         <property name="minEvictableIdleTimeMillis" value="1800000" />  
  36.         <!-- 每次evictor启动检查的空闲连接数,-2标识1/2的总空闲连接 -->  
  37.         <property name="numTestsPerEvictionRun" value="-1"></property>  
  38.         <!-- 线程池初始数量 -->  
  39.         <property name="initialSize" value="10"></property>  
  40.         <!-- 最大线程数量 -->  
  41.         <property name="maxActive" value="50"></property>  
  42.         <!-- 最大空闲线程数量 -->  
  43.         <property name="maxIdle" value="20"></property>  
  44.         <!-- 最小空闲线程数量 -->  
  45.         <property name="minIdle" value="10"></property>  
  46.         <!-- 从线程池获取一个mysql连接的最大等待时间,单位毫秒 -->  
  47.         <property name="maxWait" value="1000"></property>  
  48.     </bean>  
  49.   
  50.     <!-- 2. mybatis的SqlSession的工厂-->  
  51.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  52.         <property name="dataSource" ref="dataSource" />  
  53.         <!-- 所有配置的mybatis映射文件 -->  
  54.         <property name="mapperLocations" value="classpath:com/maven/web/mapping/*.xml" />  
  55.     </bean>  
  56.   
  57.     <!-- 3. mybatis自动扫描加载Sql接口 -->  
  58.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  59.         <property name="basePackage" value="com.maven.web.mapper"></property>  
  60.         <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>  
  61.     </bean>  
  62.   
  63.     <!-- 4. 事务管理  -->  
  64.     <bean id="transactionManager"  
  65.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  66.         <property name="dataSource" ref="dataSource"></property>  
  67.     </bean>  
  68.   
  69.     <tx:annotation-driven transaction-manager="transactionManager" />  
  70.   
  71. </beans>  

五, Spring-servlet.xml , 配置如下:

[html]  view plain  copy
  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.2.xsd    
  8.                         http://www.springframework.org/schema/context    
  9.                         http://www.springframework.org/schema/context/spring-context-4.2.xsd    
  10.                         http://www.springframework.org/schema/mvc    
  11.                         http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">  
  12.       
  13.      <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器  -->    
  14.     <context:component-scan base-package="com.maven.web.controller" />  
  15.   
  16.     <mvc:annotation-driven>  
  17.         <mvc:message-converters>  
  18.             <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">  
  19.                 <description>JSON转换器</description>  
  20.                 <property name="supportedMediaTypes">  
  21.                     <list>  
  22.                         <value>application/json;charset=UTF-8</value>    
  23.                         <value>text/html;charset=UTF-8</value>  
  24.                     </list>  
  25.                 </property>  
  26.             </bean>  
  27.         </mvc:message-converters>  
  28.     </mvc:annotation-driven>  
  29.       
  30.     <!-- 定义ViewResolver组件, 实现根据视图标识获取JSP响应 -->  
  31.     <mvc:view-resolvers>  
  32.         <mvc:jsp cache-views="false" prefix="/WEB-INF/html/" suffix=".jsp" />    
  33.     </mvc:view-resolvers>  
  34.       
  35.     <!-- 静态资源访问,不被DispatcherServlet处理 -->  
  36.     <mvc:resources mapping="jsp/**" location="/WEB-INF/jsp/" />  
  37.     <mvc:resources mapping="/js/**" location="/js/" />  
  38.       
  39.     <!-- 开启默认处理 -->    
  40.     <mvc:default-servlet-handler />  
  41.       
  42. </beans>  

=== 这里需要注意的是,两个配置文件中都开启了扫描注解包,

其中SpringMvc配置文件只扫描controller包,

而Spring配置文件则扫描除controller包以外的所有包。


六,mybatis 自动生成代码工具

这款自动生成代码的工具使用很方便,可以集成到自己的工程里面,也可以单独使用,简单来说只有三部分:

(1) 引入jar包,上文已经在pom.xml中引入了,请回顾查看

(2) 加入配置文件,mbgConfiguration.xml ,

主要是对数据库的连接配置,代码生成后的存放目录配置,以及需要生成代码的数据库对应表的配置

(3) 编写java类,加载配置文件,生成代码


七,mbgConfiguration.xml,配置如下:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE generatorConfiguration  
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
  5. <generatorConfiguration>  
  6.     <!-- 配置mysql 驱动jar包路径.用了绝对路径 -->  
  7.     <classPathEntry  
  8.        <!--jar地址-->
  9.         location="H:/repository/org/mybatis/mybatis/3.3.0/mybatis-3.3.0.jar" />  
  10.     <context id="mysql_tables " targetRuntime="MyBatis3">  
  11.         <!-- 为了防止生成的代码中有很多注释,比较难看,加入下面的配置控制 -->  
  12.         <commentGenerator>  
  13.             <property name="suppressAllComments" value="true" />  
  14.             <property name="suppressDate" value="true" />  
  15.         </commentGenerator>  
  16.         <!-- 注释控制完毕 -->  
  17.         <!-- 数据库连接 -->  
  18.         <jdbcConnection driverClass="com.mysql.jdbc.Driver"  
  19.             connectionURL="jdbc:mysql://127.0.0.1:3306/yun?characterEncoding=utf8"  
  20.             userId="root" password="centos">  
  21.         </jdbcConnection>  
  22.         <javaTypeResolver>  
  23.             <property name="forceBigDecimals" value="false" />  
  24.         </javaTypeResolver>  
  25.         <!-- 数据表对应的model 层 -->  
  26.         <javaModelGenerator targetPackage="com.maven.web.entity"  
  27.             targetProject="H:\project\com.maven.web\src\main\java">  
  28.             <property name="enableSubPackages" value="true" />  
  29.             <property name="trimStrings" value="true" />  
  30.         </javaModelGenerator>  
  31.         <!-- sql mapper 隐射配置文件 -->  
  32.         <sqlMapGenerator targetPackage="com.maven.web.mapping"  
  33.             targetProject="H:\project\com.maven.web\src\main\java">  
  34.             <property name="enableSubPackages" value="true" />  
  35.         </sqlMapGenerator>  
  36.         <!-- 在ibatis2 中是dao层,但在mybatis3中,其实就是mapper接口 -->  
  37.         <javaClientGenerator type="XMLMAPPER"
  38.            <!--工作空间的地址 -->  
  39.             targetPackage="com.maven.web.mapper" targetProject="H:\project\com.maven.web\src\main\java">  
  40.             <property name="enableSubPackages" value="true" />  
  41.         </javaClientGenerator>  
  42.         <!-- 要对那些数据表进行生成操作,必须要有一个. -->  
  43.         <table schema="mybatis" tableName="USER_INFO" domainObjectName="UserInfo"  
  44.             enableCountByExample="false" enableUpdateByExample="false"  
  45.             enableDeleteByExample="false" enableSelectByExample="false"  
  46.             selectByExampleQueryId="false">  
  47.         </table>  
  48.     </context>  
  49. </generatorConfiguration>  
八,在main函数中加载配置文件,启动生成代码,源码如下:

[java]  view plain  copy
  1. package com.maven.web.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.sql.SQLException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. import org.mybatis.generator.api.MyBatisGenerator;  
  9. import org.mybatis.generator.config.Configuration;  
  10. import org.mybatis.generator.config.xml.ConfigurationParser;  
  11. import org.mybatis.generator.exception.InvalidConfigurationException;  
  12. import org.mybatis.generator.exception.XMLParserException;  
  13. import org.mybatis.generator.internal.DefaultShellCallback;  
  14.   
  15. public class GenMain {  
  16.   
  17.     public static void main(String[] args) {  
  18.         List<String> warnings = new ArrayList<String>();  
  19.         boolean overwrite = true;  
  20.         String genCfg = "/mbgConfiguration.xml";  
  21.         File configFile = new File(GenMain.class.getResource(genCfg).getFile());  
  22.         ConfigurationParser cp = new ConfigurationParser(warnings);  
  23.         Configuration config = null;  
  24.         try {  
  25.             config = cp.parseConfiguration(configFile);  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         } catch (XMLParserException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.         DefaultShellCallback callback = new DefaultShellCallback(overwrite);  
  32.         MyBatisGenerator myBatisGenerator = null;  
  33.         try {  
  34.             myBatisGenerator = new MyBatisGenerator(config, callback, warnings);  
  35.         } catch (InvalidConfigurationException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.         try {  
  39.             myBatisGenerator.generate(null);  
  40.         } catch (SQLException e) {  
  41.             e.printStackTrace();  
  42.         } catch (IOException e) {  
  43.             e.printStackTrace();  
  44.         } catch (InterruptedException e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.     }  
  48. }  
运行后,刷新工程,就可以看到配置的目录下面已经自动生成好了代码,目录如下:


默认生成的代码已经实现基本的增删改查操作,如果需要,用户可以再自行添加方法并实现。

代码展示如下:

(1) UserInfo

[java]  view plain  copy
  1. package com.maven.web.entity;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class UserInfo {  
  6.     private Long id;  
  7.   
  8.     private String userName;  
  9.   
  10.     private String password;  
  11.   
  12.     private String email;  
  13.   
  14.     private String phone;  
  15.   
  16.     private String sex;  
  17.   
  18.     private String status;  
  19.   
  20.     private Date createTime;  
  21.   
  22.     private Date updateTime;  
  23.   
  24.     public Long getId() {  
  25.         return id;  
  26.     }  
  27.   
  28.     public void setId(Long id) {  
  29.         this.id = id;  
  30.     }  
  31.   
  32.     public String getUserName() {  
  33.         return userName;  
  34.     }  
  35.   
  36.     public void setUserName(String userName) {  
  37.         this.userName = userName == null ? null : userName.trim();  
  38.     }  
  39.   
  40.     public String getPassword() {  
  41.         return password;  
  42.     }  
  43.   
  44.     public void setPassword(String password) {  
  45.         this.password = password == null ? null : password.trim();  
  46.     }  
  47.   
  48.     public String getEmail() {  
  49.         return email;  
  50.     }  
  51.   
  52.     public void setEmail(String email) {  
  53.         this.email = email == null ? null : email.trim();  
  54.     }  
  55.   
  56.     public String getPhone() {  
  57.         return phone;  
  58.     }  
  59.   
  60.     public void setPhone(String phone) {  
  61.         this.phone = phone == null ? null : phone.trim();  
  62.     }  
  63.   
  64.     public String getSex() {  
  65.         return sex;  
  66.     }  
  67.   
  68.     public void setSex(String sex) {  
  69.         this.sex = sex == null ? null : sex.trim();  
  70.     }  
  71.   
  72.     public String getStatus() {  
  73.         return status;  
  74.     }  
  75.   
  76.     public void setStatus(String status) {  
  77.         this.status = status == null ? null : status.trim();  
  78.     }  
  79.   
  80.     public Date getCreateTime() {  
  81.         return createTime;  
  82.     }  
  83.   
  84.     public void setCreateTime(Date createTime) {  
  85.         this.createTime = createTime;  
  86.     }  
  87.   
  88.     public Date getUpdateTime() {  
  89.         return updateTime;  
  90.     }  
  91.   
  92.     public void setUpdateTime(Date updateTime) {  
  93.         this.updateTime = updateTime;  
  94.     }  
  95. }  

(2) UserInfoMapper

[java]  view plain  copy
  1. package com.maven.web.mapper;  
  2.   
  3. import org.springframework.stereotype.Repository;  
  4.   
  5. import com.maven.web.entity.UserInfo;  
  6.   
  7. @Repository  
  8. public interface UserInfoMapper {  
  9.     int deleteByPrimaryKey(Long id);  
  10.   
  11.     int insert(UserInfo record);  
  12.   
  13.     int insertSelective(UserInfo record);  
  14.   
  15.     UserInfo selectByPrimaryKey(Long id);  
  16.   
  17.     int updateByPrimaryKeySelective(UserInfo record);  
  18.   
  19.     int updateByPrimaryKey(UserInfo record);  
  20. }  

(3) UserInfoMapper.xml

[html]  view plain  copy
  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="com.maven.web.mapper.UserInfoMapper" >  
  4.   <resultMap id="BaseResultMap" type="com.maven.web.entity.UserInfo" >  
  5.     <id column="id" property="id" jdbcType="BIGINT" />  
  6.     <result column="user_name" property="userName" jdbcType="VARCHAR" />  
  7.     <result column="password" property="password" jdbcType="VARCHAR" />  
  8.     <result column="email" property="email" jdbcType="VARCHAR" />  
  9.     <result column="phone" property="phone" jdbcType="VARCHAR" />  
  10.     <result column="sex" property="sex" jdbcType="VARCHAR" />  
  11.     <result column="status" property="status" jdbcType="VARCHAR" />  
  12.     <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />  
  13.     <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />  
  14.   </resultMap>  
  15.   <sql id="Base_Column_List" >  
  16.     id, user_name, password, email, phone, sex, status, create_time, update_time  
  17.   </sql>  
  18.   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >  
  19.     select   
  20.     <include refid="Base_Column_List" />  
  21.     from user_info  
  22.     where id = #{id,jdbcType=BIGINT}  
  23.   </select>  
  24.   <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >  
  25.     delete from user_info  
  26.     where id = #{id,jdbcType=BIGINT}  
  27.   </delete>  
  28.   <insert id="insert" parameterType="com.maven.web.entity.UserInfo" >  
  29.     insert into user_info (id, user_name, password,   
  30.       email, phone, sex,   
  31.       status, create_time, update_time  
  32.       )  
  33.     values (#{id,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},   
  34.       #{email,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR},   
  35.       #{status,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}  
  36.       )  
  37.   </insert>  
  38.   <insert id="insertSelective" parameterType="com.maven.web.entity.UserInfo" >  
  39.     insert into user_info  
  40.     <trim prefix="(" suffix=")" suffixOverrides="," >  
  41.       <if test="id != null" >  
  42.         id,  
  43.       </if>  
  44.       <if test="userName != null" >  
  45.         user_name,  
  46.       </if>  
  47.       <if test="password != null" >  
  48.         password,  
  49.       </if>  
  50.       <if test="email != null" >  
  51.         email,  
  52.       </if>  
  53.       <if test="phone != null" >  
  54.         phone,  
  55.       </if>  
  56.       <if test="sex != null" >  
  57.         sex,  
  58.       </if>  
  59.       <if test="status != null" >  
  60.         status,  
  61.       </if>  
  62.       <if test="createTime != null" >  
  63.         create_time,  
  64.       </if>  
  65.       <if test="updateTime != null" >  
  66.         update_time,  
  67.       </if>  
  68.     </trim>  
  69.     <trim prefix="values (" suffix=")" suffixOverrides="," >  
  70.       <if test="id != null" >  
  71.         #{id,jdbcType=BIGINT},  
  72.       </if>  
  73.       <if test="userName != null" >  
  74.         #{userName,jdbcType=VARCHAR},  
  75.       </if>  
  76.       <if test="password != null" >  
  77.         #{password,jdbcType=VARCHAR},  
  78.       </if>  
  79.       <if test="email != null" >  
  80.         #{email,jdbcType=VARCHAR},  
  81.       </if>  
  82.       <if test="phone != null" >  
  83.         #{phone,jdbcType=VARCHAR},  
  84.       </if>  
  85.       <if test="sex != null" >  
  86.         #{sex,jdbcType=VARCHAR},  
  87.       </if>  
  88.       <if test="status != null" >  
  89.         #{status,jdbcType=VARCHAR},  
  90.       </if>  
  91.       <if test="createTime != null" >  
  92.         #{createTime,jdbcType=TIMESTAMP}<span style="font-family: Arial, Helvetica, sans-serif;">,</span>  
  93.       </if>  
  94.       <if test="updateTime != null" >  
  95.         #{updateTime,jdbcType=TIMESTAMP},  
  96.       </if>  
  97.     </trim>  
  98.   </insert>  
  99.   <update id="updateByPrimaryKeySelective" parameterType="com.maven.web.entity.UserInfo" >  
  100.     update user_info  
  101.     <set >  
  102.       <if test="userName != null" >  
  103.         user_name = #{userName,jdbcType=VARCHAR},  
  104.       </if>  
  105.       <if test="password != null" >  
  106.         password = #{password,jdbcType=VARCHAR},  
  107.       </if>  
  108.       <if test="email != null" >  
  109.         email = #{email,jdbcType=VARCHAR},  
  110.       </if>  
  111.       <if test="phone != null" >  
  112.         phone = #{phone,jdbcType=VARCHAR},  
  113.       </if>  
  114.       <if test="sex != null" >  
  115.         sex = #{sex,jdbcType=VARCHAR},  
  116.       </if>  
  117.       <if test="status != null" >  
  118.         status = #{status,jdbcType=VARCHAR},  
  119.       </if>  
  120.       <if test="createTime != null" >  
  121.         create_time = #{createTime,jdbcType=TIMESTAMP},  
  122.       </if>  
  123.       <if test="updateTime != null" >  
  124.         update_time = #{updateTime,jdbcType=TIMESTAMP},  
  125.       </if>  
  126.     </set>  
  127.     where id = #{id,jdbcType=BIGINT}  
  128.   </update>  
  129.   <update id="updateByPrimaryKey" parameterType="com.maven.web.entity.UserInfo" >  
  130.     update user_info  
  131.     set user_name = #{userName,jdbcType=VARCHAR},  
  132.       password = #{password,jdbcType=VARCHAR},  
  133.       email = #{email,jdbcType=VARCHAR},  
  134.       phone = #{phone,jdbcType=VARCHAR},  
  135.       sex = #{sex,jdbcType=VARCHAR},  
  136.       status = #{status,jdbcType=VARCHAR},  
  137.       create_time = #{createTime,jdbcType=TIMESTAMP},  
  138.       update_time = #{updateTime,jdbcType=TIMESTAMP}  
  139.     where id = #{id,jdbcType=BIGINT}  
  140.   </update>  
  141. </mapper>  
在上面生成的xml映射文件中,我对 insertSelective 方法做了些许改动,直接赋值给create_time 和 update_time 改动如下:
[html]  view plain  copy
  1. <insert id="insertSelective" parameterType="com.maven.web.entity.UserInfo" >  
  2.     insert into user_info  
  3.     <trim prefix="(" suffix=")" suffixOverrides="," >  
  4.       <if test="id != null" >  
  5.         id,  
  6.       </if>  
  7.       <if test="userName != null" >  
  8.         user_name,  
  9.       </if>  
  10.       <if test="password != null" >  
  11.         password,  
  12.       </if>  
  13.       <if test="email != null" >  
  14.         email,  
  15.       </if>  
  16.       <if test="phone != null" >  
  17.         phone,  
  18.       </if>  
  19.       <if test="sex != null" >  
  20.         sex,  
  21.       </if>  
  22.       <if test="status != null" >  
  23.         status,  
  24.       </if>  
  25.       <if test="createTime != null" >  
  26.         create_time,  
  27.       </if>  
  28.       <if test="updateTime != null" >  
  29.         update_time,  
  30.       </if>  
  31.     </trim>  
  32.     <trim prefix="values (" suffix=")" suffixOverrides="," >  
  33.       <if test="id != null" >  
  34.         #{id,jdbcType=BIGINT},  
  35.       </if>  
  36.       <if test="userName != null" >  
  37.         #{userName,jdbcType=VARCHAR},  
  38.       </if>  
  39.       <if test="password != null" >  
  40.         #{password,jdbcType=VARCHAR},  
  41.       </if>  
  42.       <if test="email != null" >  
  43.         #{email,jdbcType=VARCHAR},  
  44.       </if>  
  45.       <if test="phone != null" >  
  46.         #{phone,jdbcType=VARCHAR},  
  47.       </if>  
  48.       <if test="sex != null" >  
  49.         #{sex,jdbcType=VARCHAR},  
  50.       </if>  
  51.       <if test="status != null" >  
  52.         #{status,jdbcType=VARCHAR},  
  53.       </if>  
  54.       <if test="createTime != null" >  
  55.         now(),  
  56.       </if>  
  57.       <if test="updateTime != null" >  
  58.         now(),  
  59.       </if>  
  60.     </trim>  
  61.   </insert>  

**************************************************************************************************************************

到此,基本框架就已经搭建好了,下面我们来做简单的前后端交互,大家可以自行体会采用这种框架的便利之处。

本例采用的注解注入方式,简化xml配置文件。


九,新建controller,service 完成简单的增删查操作,代码如下:

(1) UserController

[java]  view plain  copy
  1. package com.maven.web.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestBody;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.bind.annotation.RequestMethod;  
  9. import org.springframework.web.bind.annotation.RequestParam;  
  10. import org.springframework.web.bind.annotation.ResponseBody;  
  11.   
  12. import com.maven.web.entity.UserInfo;  
  13. import com.maven.web.service.impl.UserService;  
  14.   
  15. @Controller  
  16. @RequestMapping("/user")  
  17. public class UserController {  
  18.       
  19.     @Resource  
  20.     private UserService userService;  
  21.       
  22.     @ResponseBody  
  23.     @RequestMapping(value="/insert", method=RequestMethod.POST)  
  24.     public String insert(@RequestBody UserInfo userInfo){  
  25.         if(userInfo.getStatus()==null){  
  26.             userInfo.setStatus("0");  
  27.         }  
  28.         Integer count = userService.insert(userInfo);  
  29.         if(count>0){  
  30.             return "保存用户信息成功";  
  31.         }  
  32.         return "保存用户信息失败";  
  33.     }  
  34.       
  35.     @ResponseBody  
  36.     @RequestMapping(value="/select", method=RequestMethod.GET)  
  37.     public String select(@RequestParam Long uid){  
  38.         UserInfo userInfo = userService.select(uid);  
  39.         if(userInfo!=null){  
  40.             return "您要查找的用户名是"+userInfo.getUserName();  
  41.         }  
  42.         return "查找用户失败";  
  43.     }  
  44.       
  45.     @ResponseBody  
  46.     @RequestMapping(value="/delete", method=RequestMethod.DELETE)  
  47.     public String delete(@RequestParam Long uid){  
  48.         Integer count = userService.delete(uid);  
  49.         if(count>0){  
  50.             return "删除用户信息成功";  
  51.         }  
  52.         return "删除用户信息失败";  
  53.     }  
  54.   
  55. }  
(2) UserService

[java]  view plain  copy
  1. package com.maven.web.service.impl;  
  2.   
  3. import com.maven.web.entity.UserInfo;  
  4.   
  5. public interface UserService {  
  6.   
  7.     Integer insert(UserInfo userInfo);  
  8.   
  9.     Integer delete(Long uid);  
  10.   
  11.     UserInfo select(Long uid);  
  12.   
  13. }  
(3) UserServiceImpl

[java]  view plain  copy
  1. package com.maven.web.service.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8. import com.maven.web.entity.UserInfo;  
  9. import com.maven.web.mapper.UserInfoMapper;  
  10.   
  11. @Service  
  12. @Transactional  
  13. public class UserServiceImpl implements UserService {  
  14.       
  15.     @Resource  
  16.     private UserInfoMapper userInfoMapper;  
  17.   
  18.     public Integer insert(UserInfo userInfo) {  
  19.         return userInfoMapper.insertSelective(userInfo);  
  20.     }  
  21.   
  22.     public Integer delete(Long uid) {  
  23.         return userInfoMapper.deleteByPrimaryKey(uid);  
  24.     }  
  25.   
  26.     public UserInfo select(Long uid) {  
  27.         return userInfoMapper.selectByPrimaryKey(uid);  
  28.     }  
  29.   
  30. }  

十,启动tomcat,测试,这里我用的是google应用插件,postman

(1) 新增用户信息,插入数据,这里传递的参数是JSON字符串格式,POST请求

后台用@RequestBody会自动将接收到的JSON格式转换成UserInfo对象,返回结果如下:


(2) 查询用户信息,GET请求


(3) 删除用户请求,DELETE请求



到此演示就全部结束了,关于SpringMvc接收参数的方式,大家可以跳转链接进行学习:点击打开链接

本例源码下载地址:https://github.com/wx-Mall/public.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值