• spring+springmvc+mybatis整合框架搭建


    由于例子是基于Maven搭建的,所以首先是pom.xml文件的依赖信息;

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.zte.ems</groupId>
      <artifactId>spring-mybatis-springmvc</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>spring-mybatis-springmvc Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <properties>
      <!-- lib version -->
      <!-- base setting -->  
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
            <project.build.locales>zh_CN</project.build.locales>  
            <project.build.jdk>1.7</project.build.jdk>  
      
            <!-- plugin setting -->  
            <mybatis.generator.generatorConfig.xml>${basedir}/src/test/resources/generatorConfig.xml</mybatis.generator.generatorConfig.xml>  
            <mybatis.generator.generatorConfig.properties>file:///${basedir}/src/test/resources/generatorConfig.properties</mybatis.generator.generatorConfig.properties>  
      
            <!-- plugin versions -->  
            <plugin.mybatis.generator>1.3.1</plugin.mybatis.generator>  
            <plugin.maven-compiler>3.1</plugin.maven-compiler>  
      
            <!-- lib versions -->  
            <junit.version>4.11</junit.version>  
            <spring.version>4.0.2.RELEASE</spring.version>  
            <mybatis.version>3.2.2</mybatis.version>  
            <mybatis.spring.version>1.2.2</mybatis.spring.version>  
            <mysql.connector.version>5.0.5</mysql.connector.version>  
            <postgresql.version>9.1-901.jdbc4</postgresql.version>  
            <slf4j.version>1.6.6</slf4j.version>  
            <log4j.version>1.2.12</log4j.version>  
            <httpclient.version>4.1.2</httpclient.version>  
            <jackson.version>1.9.13</jackson.version>  
            <c3p0.version>0.9.1.2</c3p0.version>  
            <druid.version>1.0.5</druid.version>  
            <tomcat.jdbc.version>7.0.53</tomcat.jdbc.version>  
            <jstl.version>1.2</jstl.version>  
            <google.collections.version>1.0</google.collections.version>  
            <cglib.version>3.1</cglib.version>  
            <shiro.version>1.2.3</shiro.version>  
            <commons.fileupload.version>1.3.1</commons.fileupload.version>  
            <commons.codec.version>1.9</commons.codec.version>  
            <commons.net.version>3.3</commons.net.version>  
            <aspectj.version>1.6.12</aspectj.version>  
            <netty.version>4.0.18.Final</netty.version>  
            <hibernate.validator.version>5.1.1.Final</hibernate.validator.version>  
      </properties>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</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-aop</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-test</artifactId>  
                <version>${spring.version}</version>  
            </dependency>  
            <!-- aspectJ依赖 -->
               <!-- aspectjweaver -->  
            <dependency>  
                <groupId>org.aspectj</groupId>  
                <artifactId>aspectjweaver</artifactId>  
                <version>${aspectj.version}</version>  
            </dependency>  
            <dependency>  
                <groupId>org.aspectj</groupId>  
                <artifactId>aspectjrt</artifactId>  
                <version>${aspectj.version}</version>  
            </dependency>  
            <!-- springframe end -->  
        
        <!-- 添加mybatis依赖 -->
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis</artifactId>  
                <version>${mybatis.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.mybatis</groupId>  
                <artifactId>mybatis-spring</artifactId>  
                <version>${mybatis.spring.version}</version>  
            </dependency>  
            
            <dependency>  
                <groupId>org.mybatis.generator</groupId>  
                <artifactId>mybatis-generator-core</artifactId>  
                <version>1.3.2</version>  
                <type>jar</type>  
                <scope>test</scope>  
            </dependency> 
            <!--mybatis end-->  
        
        <!-- 添加springmvc依赖 -->
        
        <!-- 添加jsp、servlet依赖 -->
        <!-- servlet api -->  
            <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>javax.servlet-api</artifactId>  
                <version>3.0.1</version>  
                <scope>provided</scope>  
            </dependency>  
      
            <!-- jstl -->  
            <dependency>  
                <groupId>javax.servlet</groupId>  
                <artifactId>jstl</artifactId>  
                <version>${jstl.version}</version>  
            </dependency>  
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        
        <!-- 添加mysQL依赖 -->
        <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>${mysql.connector.version}</version>
      </dependency>
      <!-- 数据源的配置 -->
       <dependency>  
                <groupId>com.alibaba</groupId>  
                <artifactId>druid</artifactId>  
                <version>${druid.version}</version>  
          </dependency>
          <!-- 添加jackson依赖 -->  
            <dependency>  
                <groupId>org.codehaus.jackson</groupId>  
                <artifactId>jackson-mapper-asl</artifactId>  
                <version>${jackson.version}</version>  
            </dependency>  
            <!-- 添加log相关依赖 -->
            <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 --> 
             <!-- cglib -->  
            <dependency>  
                <groupId>cglib</groupId>  
                <artifactId>cglib-nodep</artifactId>  
                <version>${cglib.version}</version>  
            </dependency>  
            
            <!-- start apache -->  
            <dependency>  
                <groupId>commons-fileupload</groupId>  
                <artifactId>commons-fileupload</artifactId>  
                <version>${commons.fileupload.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>org.apache.httpcomponents</groupId>  
                <artifactId>httpclient</artifactId>  
                <version>${httpclient.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>commons-codec</groupId>  
                <artifactId>commons-codec</artifactId>  
                <version>${commons.codec.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>commons-net</groupId>  
                <artifactId>commons-net</artifactId>  
                <version>${commons.net.version}</version>  
            </dependency>  
      
            <dependency>  
                <groupId>commons-logging</groupId>  
                <artifactId>commons-logging</artifactId>  
                <version>1.1.3</version>  
            </dependency>  
            <dependency>  
                <groupId>commons-collections</groupId>  
                <artifactId>commons-collections</artifactId>  
                <version>3.2.1</version>  
            </dependency>  
      
            <!-- end apache -->  
      </dependencies>
    
      
      <build>
        <finalName>spring-mybatis-springmvc</finalName>
    
        <pluginManagement>
            <plugins>
            <!--Maven编译插件 配置-->  
                <plugin>  
                    <groupId>org.apache.maven.plugins</groupId>  
                    <artifactId>maven-compiler-plugin</artifactId>  
                    <version>${plugin.maven-compiler}</version>  
                    <configuration>  
                        <source>${project.build.jdk}</source>  
                        <target>${project.build.jdk}</target>  
                        <encoding>${project.build.sourceEncoding}</encoding>  
                    </configuration>  
                </plugin>  
            <!-- 配置tomcat插件 -->
                <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                  <version>2.2</version>
                
                    <configuration>
                        <path>/ssm</path>
                        <port>8080</port>
                        <uriEncoding>UTF-8</uriEncoding>
                        <url>http://localhost:8080/manager/text</url>
                        <server>tomcat7</server>
                    </configuration>
                </plugin>
                
                  <!-- Mybatis generator代码生成插件 配置 -->  
                <plugin>  
                    <groupId>org.mybatis.generator</groupId>  
                    <artifactId>mybatis-generator-maven-plugin</artifactId>  
                    <version>${plugin.mybatis.generator}</version>  
                    <configuration>  
                        <configurationFile>${mybatis.generator.generatorConfig.xml}</configurationFile>  
                        <overwrite>true</overwrite>  
                        <verbose>true</verbose>  
                    </configuration>  
                </plugin> 
            </plugins>
        </pluginManagement>
          <!--配置Maven 对resource文件 过滤 -->  
            <resources>  
                <resource>  
                    <directory>src/main/resources</directory>  
                    <includes>  
                        <include>**/*.properties</include>  
                        <include>**/*.xml</include>  
                    </includes>  
                    <filtering>true</filtering>  
                </resource>  
                <resource>  
                    <directory>src/main/java</directory>  
                    <includes>  
                        <include>**/*.properties</include>  
                        <include>**/*.xml</include>  
                    </includes>  
                    <filtering>true</filtering>  
                </resource>  
            </resources>  
      </build>
    
    </project>

    第一步:配置mybatis:mybatis-config.xml

    <?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>  
        <typeAliases>  
            <package name="com.zte.ems.model"/>   
        </typeAliases>  
    </configuration>

    第二步:配置spring相关的三个xml文件

      (1)spring-dao.xml文件的配置。该文件主要配置了数据库相关的信息,以及spring-mybaits的信息;

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
     
    <!-- 数据库连接池 -->
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
    
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="maxActive" value="10" />
    <property name="minIdle" value="5" />
    </bean>
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    <property name="mapperLocations" value="classpath:com/zte/ems/dao/*.xml"></property> 
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置扫描包,加载mapper代理对象 -->
     <!-- 这个配置隐式注册了多个对注解进行解析处理的处理器 -->  
          <context:annotation-config/>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.zte.ems.dao"></property>
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>
    </beans>

      (2)spring-service.xml文件的配置,这个配置文件主要配置了扫描哪些包下的类让Spring容器管理;

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
      <!-- 这个配置隐式注册了多个对注解进行解析处理的处理器 -->  
          <context:annotation-config/>
    <!-- 扫描包加载Service实现类 -->
    <context:component-scan base-package="com.zte.ems.service"/>
    </beans>

      (3)spring-trans.xml文件的配置,这个文件主要配置了aop切面和事务相关的信息;

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
     
    <!-- 事务管理器 -->
    <bean id="transactionManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 数据源 -->
    <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <!-- 传播行为 -->
    <tx:method name="save*" propagation="REQUIRED" />
    <tx:method name="insert*" propagation="REQUIRED" />
    <tx:method name="add*" propagation="REQUIRED" />
    <tx:method name="create*" propagation="REQUIRED" />
    <tx:method name="delete*" propagation="REQUIRED" />
    <tx:method name="update*" propagation="REQUIRED" />
    <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
    <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
    <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
    </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
    <aop:advisor advice-ref="txAdvice"
    pointcut="execution(* com.zte.ems.service.*.*(..))" />
    </aop:config>
    </beans>

    第三步:springmvc-config.xml文件的配置;

    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
           xmlns:aop="http://www.springframework.org/schema/aop"  
           xmlns:context="http://www.springframework.org/schema/context"  
           xmlns:mvc="http://www.springframework.org/schema/mvc"  
           xmlns:tx="http://www.springframework.org/schema/tx"  
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xmlns:p="http://www.springframework.org/schema/p"  
           xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd   
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd   
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">  
          <mvc:annotation-driven/>  
        <!-- 开启controller注解支持 -->
        <!-- use-default-filters="false" 只扫描指定的注解 -->
        <context:component-scan base-package="com.zte.ems.controllers" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>  
      
        <!-- 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的 -->    
        
      
        <!-- 如果当前请求为“/”时,则转发到“/helloworld/index” -->
        <mvc:view-controller path="/" view-name="forward:/helloworld/index"/> 
        <!-- 静态资源映射 -->
        <mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
        <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
        <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/" />
        <mvc:resources mapping="/plugins/**" location="/WEB-INF/plugins/" />
        <mvc:resources mapping="images/**" location="/WEB-INF/images/" />
        <!-- 当上面要访问的静态资源不包括在上面的配置中时,则根据此配置来访问 -->
        <mvc:default-servlet-handler/>
      
        <!-- 配置视图解析器,并指定视图所在的文件夹  -->
        <bean  id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 
           <property name="contentType" value="text/html"/>        
           <property name="prefix" value="/WEB-INF/views/"/><!-- WEB-INF/views/ -->
           <property name="suffix" value=".jsp"/>
        </bean>
    </beans>  

    第四步:web.xml文件的配置,在这个文件中主要配置spring和springmvc;

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="tomcat" version="2.5">
    
     <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
       <!-- 配置spring -->
       <context-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>  
                classpath:spring-*.xml  
            </param-value>  
        </context-param>  
        <!-- 配置Spring上下文监听器 -->  
        <listener>  
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
        </listener>  
        
        <!-- 解决post乱码 -->
    <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
      <!-- 配置springmvc -->
      <servlet>  
            <servlet-name>ssm</servlet-name>  
            <!-- DispatcherServlet:前端控制器,主要就是拦截请求,然后调用对应的Controller和Action -->
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
            <init-param>  
                <param-name>contextConfigLocation</param-name>  
                <param-value>classpath:springmvc-config.xml</param-value>  
            </init-param>  
            <!-- <load-on-startup>是启动顺序,让这个Servlet随Servletp容器一起启动,必须放在<servlet> 配置的最后。 -->
            <load-on-startup>1</load-on-startup>  
        </servlet>  
       <servlet-mapping>
            <!-- 指定配置的是哪个servlet -->
            <servlet-name>ssm</servlet-name>
            <!-- 指定拦截哪些请求到该servlet,这里配置的是拦截全部请求 -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
    </web-app>

    第五步:编写代码

    1、编写POJO类:

    package com.zte.ems.model;
    
    public class Person {
        private Integer id;
    
        private String name;
    
        private Integer sex;
    
        private String email;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name == null ? null : name.trim();
        }
    
        public Integer getSex() {
            return sex;
        }
    
        public void setSex(Integer sex) {
            this.sex = sex;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email == null ? null : email.trim();
        }
    }

    2、使用mybatis逆向工程根据数据库中Person表自动生成PersonMapper.java 和PersonMapper.xml

    package com.zte.ems.dao;
    
    import com.zte.ems.model.Person;
    import com.zte.ems.model.PersonExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
    
    public interface PersonMapper {
        int countByExample(PersonExample example);
    
        int deleteByExample(PersonExample example);
    
        int deleteByPrimaryKey(Integer id);
    
        int insert(Person record);
    
        int insertSelective(Person record);
    
        List<Person> selectByExample(PersonExample example);
    
        Person selectByPrimaryKey(Integer id);
    
        int updateByExampleSelective(@Param("record") Person record, @Param("example") PersonExample example);
    
        int updateByExample(@Param("record") Person record, @Param("example") PersonExample example);
    
        int updateByPrimaryKeySelective(Person record);
    
        int updateByPrimaryKey(Person record);
    }
    <?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="com.zte.ems.dao.PersonMapper" >
      <resultMap id="BaseResultMap" type="com.zte.ems.model.Person" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="sex" property="sex" jdbcType="INTEGER" />
        <result column="email" property="email" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Example_Where_Clause" >
        <where >
          <foreach collection="oredCriteria" item="criteria" separator="or" >
            <if test="criteria.valid" >
              <trim prefix="(" suffix=")" prefixOverrides="and" >
                <foreach collection="criteria.criteria" item="criterion" >
                  <choose >
                    <when test="criterion.noValue" >
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue" >
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue" >
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue" >
                      and ${criterion.condition}
                      <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Update_By_Example_Where_Clause" >
        <where >
          <foreach collection="example.oredCriteria" item="criteria" separator="or" >
            <if test="criteria.valid" >
              <trim prefix="(" suffix=")" prefixOverrides="and" >
                <foreach collection="criteria.criteria" item="criterion" >
                  <choose >
                    <when test="criterion.noValue" >
                      and ${criterion.condition}
                    </when>
                    <when test="criterion.singleValue" >
                      and ${criterion.condition} #{criterion.value}
                    </when>
                    <when test="criterion.betweenValue" >
                      and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                    </when>
                    <when test="criterion.listValue" >
                      and ${criterion.condition}
                      <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                        #{listItem}
                      </foreach>
                    </when>
                  </choose>
                </foreach>
              </trim>
            </if>
          </foreach>
        </where>
      </sql>
      <sql id="Base_Column_List" >
        id, name, sex, email
      </sql>
      <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.zte.ems.model.PersonExample" >
        select
        <if test="distinct" >
          distinct
        </if>
        <include refid="Base_Column_List" />
        from person
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null" >
          order by ${orderByClause}
        </if>
      </select>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from person
        where id = #{id,jdbcType=INTEGER}
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from person
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <delete id="deleteByExample" parameterType="com.zte.ems.model.PersonExample" >
        delete from person
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
      </delete>
      <insert id="insert" parameterType="com.zte.ems.model.Person" >
        insert into person (id, name, sex, 
          email)
        values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER}, 
          #{email,jdbcType=VARCHAR})
      </insert>
      <insert id="insertSelective" parameterType="com.zte.ems.model.Person" >
        insert into person
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="name != null" >
            name,
          </if>
          <if test="sex != null" >
            sex,
          </if>
          <if test="email != null" >
            email,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="name != null" >
            #{name,jdbcType=VARCHAR},
          </if>
          <if test="sex != null" >
            #{sex,jdbcType=INTEGER},
          </if>
          <if test="email != null" >
            #{email,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <select id="countByExample" parameterType="com.zte.ems.model.PersonExample" resultType="java.lang.Integer" >
        select count(*) from person
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
      </select>
      <update id="updateByExampleSelective" parameterType="map" >
        update person
        <set >
          <if test="record.id != null" >
            id = #{record.id,jdbcType=INTEGER},
          </if>
          <if test="record.name != null" >
            name = #{record.name,jdbcType=VARCHAR},
          </if>
          <if test="record.sex != null" >
            sex = #{record.sex,jdbcType=INTEGER},
          </if>
          <if test="record.email != null" >
            email = #{record.email,jdbcType=VARCHAR},
          </if>
        </set>
        <if test="_parameter != null" >
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByExample" parameterType="map" >
        update person
        set id = #{record.id,jdbcType=INTEGER},
          name = #{record.name,jdbcType=VARCHAR},
          sex = #{record.sex,jdbcType=INTEGER},
          email = #{record.email,jdbcType=VARCHAR}
        <if test="_parameter != null" >
          <include refid="Update_By_Example_Where_Clause" />
        </if>
      </update>
      <update id="updateByPrimaryKeySelective" parameterType="com.zte.ems.model.Person" >
        update person
        <set >
          <if test="name != null" >
            name = #{name,jdbcType=VARCHAR},
          </if>
          <if test="sex != null" >
            sex = #{sex,jdbcType=INTEGER},
          </if>
          <if test="email != null" >
            email = #{email,jdbcType=VARCHAR},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.zte.ems.model.Person" >
        update person
        set name = #{name,jdbcType=VARCHAR},
          sex = #{sex,jdbcType=INTEGER},
          email = #{email,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
      </update>
    </mapper>

    3、编写Service代码:

    package com.zte.ems.service;
    import java.util.List;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import com.zte.ems.dao.PersonMapper;
    import com.zte.ems.model.Person;
    import com.zte.ems.model.PersonExample;
    import com.zte.ems.model.PersonExample.Criteria;
    
    @Service // 表明这个一个受IOC管理的Service类
    public class MyService {
        @Autowired // 自动注入一个类
        private PersonMapper personMapper;
        public Person getPerson(int id) {
            // 添加查询条件
            PersonExample example = new PersonExample();
            Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(id);
            List<Person> list = personMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                Person person = list.get(0);
                return person;
            }
            return null;
        }
    }

    4、编写Controller代码:

    package com.zte.ems.controllers;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;import com.zte.ems.model.Person;
    import com.zte.ems.service.MyService;
    
    @Controller // 表明这是一个控制器类
    @RequestMapping("/admin")
    
    public class PageController {
        @Autowired
        private MyService myService;
        @Autowired
        private MyMapper myMapper;
    
        @RequestMapping("/index")
        public String shouIndex() {
            return "success";
        }
        @ResponseBody // @ResponseBody该注解表示以json形式输出
        @RequestMapping("/queryperson/{id}")
        public Person getPerson(@PathVariable int id) {
            Person person = myService.getPerson(id);
            return person;
        }
    }

    最终的目录结构如下图所示:

  • 相关阅读:
    BZOJ 2190: [SDOI2008]仪仗队
    BZOJ 3195: [Jxoi2012]奇怪的道路
    【BZOJ-1068】压缩 区间DP
    【BZOJ-1103】大都市meg 树状数组 + DFS序
    【BZOJ-4326】运输计划 树链剖分 + 树上差分 + 二分
    【BZOJ-3721】Final Bazarek 贪心
    【BZOJ-4690】Never Wait For Weights 带权并查集
    【BZOJ-2503】相框 并查集 + 分类讨论
    【BZOJ-3653】谈笑风生 DFS序 + 可持久化线段树
    【BZOJ-3252】攻略 DFS序 + 线段树 + 贪心
  • 原文地址:https://www.cnblogs.com/wrong5566/p/5964716.html
Copyright © 2020-2023  润新知