SSM 博客之环境搭建

上一次完成的 SSM 个人博客,由于时间的问题,没法及时整理,所以现在我要来一步一步回忆,我是怎么完成这个小项目的。

上一篇博客的地址

要使用 SSM 来开发个人博客,第一步就是整合 SSM 环境

  • 我使用的 IDE 是 MyEclipse for Spring 2014
  • tomcat7
  • java version : 1.8.0_101
  • spring-*-4.3.4.RELEASE.jar
  • mybatis-3.4.1.jar
  • mybatis-spring-1.3.0.jar

关于 SSM 的整合教程,网上的资源丰富,我是看了一个视频教程,那个教程免费而且挺好的。参考我的另外一篇 博文

或者参考 GitHub 上的教程: https://github.com/liyifeng1994/ssm

为了简便,我用的是 junit 的单元测试,下面给出配置文件的代码 applicationContext.xml :

<?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:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
    <!-- 扫描 service 包下的所有 Service 组件类 -->
    <context:component-scan base-package="service"></context:component-scan>

    <!-- 配置数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/jspblog"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="username" value="root"></property>
        <property name="password" value="XXXXX"></property>
    </bean>

    <!-- sqlSessionFactory 工厂类 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引用数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- Mybatis 逆向生成 xml 数据库配置文件 -->
        <property name="mapperLocations">
            <array>
                <value>classpath:mapping/*.xml</value>
            </array>
        </property>
        <!-- 使用分页插件的配置 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
                    <!-- 
                         helperDialect:分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。
                         reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0
                          时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根
                          据参数进行查询。
                         supportMethodsArguments:支持通过 Mapper 接口参数来传递分页参数,默认值false 
                         utoRuntimeDialect:默认值为 false。设置为 true 时,允许在运行时根据多数据源自动
                         识别对应方言的分页 
                         params:为了支持startPage(Object params)方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值,
                          可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值, 默认值为
                          pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;
                          pageSizeZero=pageSizeZero
                     -->

                    <property name="properties">
                        <value>
                            helperDialect=mysql
                            reasonable=true
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!-- Mybatis 的配置,给出 mapper 接口类的基础包,运行时 Mybatis 会生成代理类对象, 引用上面的工厂类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="mapping"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!-- 面向切面编程的配置 -->
    <aop:aspectj-autoproxy />

    <aop:config>
        <aop:pointcut id="appService" expression="execution(* service..*Service*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="appService" />
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <!-- 声明式事务管理 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

SpringMVC 的配置文件, springMVC-servlet.xml :

<?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:aop="http://www.springframework.org/schema/aop" xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

    <!-- 配置文件上传功能  -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="2048000000" />
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
         <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

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

    <!-- 将springmvc 不能处理的请求交给 tomcat -->
     <mvc:default-servlet-handler />
    <!-- 这个基于注解的配置一定要写,不然 controller 无法工作 -->
    <mvc:annotation-driven>
    <!--    <mvc:message-converters>
             <bean class="org.springframework.http.converter.ResourceHttpMessageConverter" >
             </bean>
             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
                 <property name="supportedMediaTypes">
                  <list>
                   <value>text/html;charset=UTF-8</value>
                   <value>application/json;charset=UTF-8</value>
                  </list>
                </property>
            </bean>
        </mvc:message-converters> -->
    </mvc:annotation-driven>

    <!-- 避免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>

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
            </list>
        </property>
    </bean>

    <!-- spring-mvc jsp视图解析器 -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix"
        value=".jsp"></property> </bean>

        <!-- 配置静态资源 -->
        <mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
        <mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
        <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
</beans>

Mybatis 的配置文件,是空的,因为全部的配置基本在 Spring 中配置,分页插件一定要在 Spring 配置,交给 Spring 管理,因为写在 Mybatis 配置文件会报错。但是还是给出来,因为有一些命名规则还是可以选择配置的:

<?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>
    <!-- 下面的配置可以不用,因为连接数据库等信息是在 Spring 4 配置文件中进行定义 -->
    <!--   <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssmblog"/>
                <property name="username" value="root"/>
                <property name="password" value="XXXX"/>
            </dataSource>
        </environment>
    </environments> -->
<!--    <mappers>
        <mapper resource="mapping/IUserinfoMapping.xml"/>
    </mappers>  -->

        <!--    - 配置全局属性 
    <settings>
         使用jdbc的getGeneratedKeys获取数据库自增主键值 
        <setting name="useGeneratedKeys" value="true" />

        <setting name="useColumnLabel" value="true" />

        开启驼峰命名转换:Table{create_time} -> Entity{createTime}
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
 -->
<!--    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="helperDialect" value="mysql"/>
            <property name="reasonable" value="true"/>
            <property name="supportMethodsArguments" value="true"/>
            <property name="autoRuntimeDialect" value="true"/>
        </plugin>
    </plugins> -->
</configuration>

Mybatis 支持逆向生成 mapper 等文件,简化开发的过程,下面是配置文件,运行方法可以在 eclipse 安装插件运行 和 命令行运行命令,这里就省略了。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
  <context id="context1">
     <!-- 数据库连接 -->
    <jdbcConnection connectionURL="jdbc:mysql://localhost:3306/jspblog" driverClass="com.mysql.jdbc.Driver" password="XXXXX" userId="root" />
    <!-- 生成 entity 类, 也就是对应数据库数据表行记录的类 -->
    <javaModelGenerator targetPackage="entity" targetProject="SSMBlog" />
    <!-- 生成操作数据库 xml 配置文件 -->
    <sqlMapGenerator targetPackage="mapping" targetProject="SSMBlog" />
    <!-- 生成 xml 配置文件对应的接口类, 相当于 Dao 接口-->
    <javaClientGenerator targetPackage="mapping" targetProject="SSMBlog" type="XMLMAPPER" />

    <!-- 对 jspblog 数据库的 users 表进行逆向 -->
    <table schema="jspblog" tableName="users">
      <generatedKey column="id" sqlStatement="mysql" identity="true" />
    </table> 

  </context>
</generatorConfiguration>

表的结构:

2

下面给出 web.xml 文件:

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SSMBlog</display-name>
  <!-- 这个配置是为了获取tomcat的根目录 -->
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>editormd.root</param-value>
  </context-param>

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

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

    <!-- 防止中文乱码 -->
     <filter>
        <filter-name>charFilter</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>charFilter</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>

   <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


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

Users 类:

package entity;

public class Users {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.id
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    private Integer id;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.username
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    private String username;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column users.password
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    private String password;



    public Users() {
    }

    public Users(String un, String pw) {
        username = un;
        password = pw;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.id
     *
     * @return the value of users.id
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public Integer getId() {
        return id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.id
     *
     * @param id the value for users.id
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.username
     *
     * @return the value of users.username
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public String getUsername() {
        return username;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.username
     *
     * @param username the value for users.username
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column users.password
     *
     * @return the value of users.password
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public String getPassword() {
        return password;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column users.password
     *
     * @param password the value for users.password
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    public void setPassword(String password) {
        this.password = password;
    }
}

UserMapper.xml 配置文件:

<?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="mapping.UsersMapper">
  <resultMap id="BaseResultMap" type="entity.Users">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    id, username, password
  </sql>
  <select id="selectByExample" parameterType="entity.UsersExample" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    select 
    <include refid="Base_Column_List" />
    from users
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    delete from users
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="entity.UsersExample">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    delete from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="entity.Users">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into users (username, password)
    values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="entity.Users">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into users
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="entity.UsersExample" resultType="java.lang.Long">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    select count(*) from users
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    update users
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.username != null">
        username = #{record.username,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    update users
    set id = #{record.id,jdbcType=INTEGER},
      username = #{record.username,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="entity.Users">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    update users
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="entity.Users">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Mon Dec 18 10:49:53 CST 2017.
    -->
    update users
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

userMapper.java 接口类:

package mapping;

import entity.Users;
import entity.UsersExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UsersMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    long countByExample(UsersExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int deleteByExample(UsersExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int deleteByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int insert(Users record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int insertSelective(Users record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    List<Users> selectByExample(UsersExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    Users selectByPrimaryKey(Integer id);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int updateByExampleSelective(@Param("record") Users record, @Param("example") UsersExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int updateByExample(@Param("record") Users record, @Param("example") UsersExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int updateByPrimaryKeySelective(Users record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table users
     *
     * @mbg.generated Mon Dec 18 10:49:53 CST 2017
     */
    int updateByPrimaryKey(Users record);
}

UserService 类:

package service;

import mapping.UsersMapper;

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

import entity.Users;

@Service
public class UserService {
    @Autowired
    private UsersMapper usersMapper;

    // 返回 指定 id 的 User 对象
    public Users selectUserById(int id) {
        return usersMapper.selectByPrimaryKey(id);
    }
}

到此配置环境基本完成了,下面写一个测试类进行测试:

package test;

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

import entity.Users;
import service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
// 加载 Spring 的配置文件, applicationContext.xml
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSSM extends AbstractJUnit4SpringContextTests {
    @Autowired
    private UserService userService;

    @Test
    public  void testSSM() {
        Users user = userService.selectUserById(1);
        System.out.println("user username = " + user.getUsername()
                + " user password = " + user.getPassword());
    }
}

使用的是 Juni4 和 Spring 的单元测试类, 继承 AbstractJUnit4SpringContextTests 抽象类。使用 junit-4.12.jar 和 hamcrest-core-1.3.jar。

运行结果 :

3

这个根据你表的记录,我的行记录是 id 为 1, username 和 password 都为 test。

新建的是 Web Project, 项目的目录结构是 :

4

5

至此,啰里啰唆的配置完了 SSM 环境。

博客项目完整地址

个人公众号:

6

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值