1. 程式人生 > >SSM 整合開發+通用的增刪改查實現

SSM 整合開發+通用的增刪改查實現

        前一段時間開發java web專案都是採用的SSH框架,開發中發現在使用Hibernate做持久層開發的時候用法不夠靈活,過於笨重,因此,改用MyBaties,結合Spring、SpringMvc框架,現將配置過程梳理如下:

一、專案結構

    專案整體結構如上所示,

    java資料夾下存放所有的class檔案,包含mybaties的mapper 檔案。

    resource資料夾存放一些與配置相關的檔案:

  •     如spring的bean配置檔案applicationContext.xml,
  •     用於配置資料庫連線的配置檔案jdbc.properties,
  •     用於日誌列印的log4j配置檔案log4j.properties,
  •     用於儲存一些系統配置的系統配置檔案sysconfig.properties,
  •     mybaties的配置檔案mybatiesConfig.xml。

二、詳細配置

1、maven配置檔案pom.xml檔案配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ssm</groupId>
    <artifactId>com.ssm</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <spring-version>4.2.3.release</spring-version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</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-beans</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</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-instrument</artifactId>-->
            <!--<version>${spring-version}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring-version}</version>
        </dependency>

        <!-- Spring Mvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <!-- Spring orm-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring-version}</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!-- jdbc -->
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
        <!-- sql server-->
        <dependency>
            <groupId>com.microsoft</groupId>
            <artifactId>sqljdbc</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- Json parse-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.9</version>
        </dependency>
        <!--utils -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>
            <!--map bean converter-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.7.0</version>
        </dependency>
        <!-- data page -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>4.2.1</version>
        </dependency>
        <!--log -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <!-- 特別注意,以下這部分配置不可缺少,如果不配置將會無法在打包時
        將mybaties的mapper 檔案打包進war包,導致報錯!!!-->
    <build>
        <resources>
            <!--編譯之後包含xml-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>com/ssm/maps/**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

2、配置Spring核心配置檔案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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 1、引入資料庫配置檔案 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 2、配置資料庫連線 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置連線池屬性,屬性值從資料庫連線配置檔案中獲取 -->
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.connectionURL}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!-- c3p0連線池的私有屬性 -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- 關閉連線後不自動commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 獲取連線超時時間 -->
        <property name="checkoutTimeout" value="10000" />
        <!-- 當獲取連線失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!-- 3、配置SqlSessionFactory物件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入資料庫連線池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBaties全域性配置檔案:mybatisConfig.xml -->
        <property name="configLocation" value="classpath:mybatisConfig.xml" />
        <!-- 掃描entity包 使用別名 -->
        <property name="typeAliasesPackage" value="com.ssm.bean"/>
        <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
        <property name="mapperLocations" value="classpath:com/ssm/maps/**/*.xml" />
    </bean>

    <!-- 4、配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 給出需要掃描Dao介面包 -->
        <property name="basePackage" value="com.ssm.dao" />
    </bean>

    <!-- 5、開啟service 註解掃描-->
    <context:component-scan base-package="com.ssm.service" />

    <!-- 6、配置事務 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 7、方法自動注入事務,原則為以特定單詞開頭的方法自動注入事務處理,無需手動提交事務 -->
    <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
        <property name="transactionManager" ref="transactionManager" />
        <property name="transactionAttributes">
            <props>
                <prop key="get*">
                    readOnly,ISOLATION_DEFAULT,-Exception
                </prop>
                <prop key="query*">
                    readOnly,ISOLATION_DEFAULT,-Exception
                </prop>
                <prop key="find*">
                    readOnly,ISOLATION_DEFAULT,-Exception
                </prop>
                <prop key="search*">
                    readOnly,ISOLATION_DEFAULT,-Exception
                </prop>
                <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>

                <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>

                <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="do*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="set*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="edit*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="process">PROPAGATION_REQUIRED,-Exception</prop>

                <prop key="*">
                    PROPAGATION_SUPPORTS,ISOLATION_DEFAULT,-Exception
                </prop>
            </props>
        </property>
    </bean>
</beans>

3、資料庫配置檔案jdbc.properties

#Oracle database
#jdbc.driverClass=oracle.jdbc.driver.OracleDriver
#jdbc.connectionURL=jdbc:oracle:thin:@//localhost:1521/ssmbase
#jdbc.username=LOUIS
#jdbc.password=123456

#SqlServer database
#jdbc.driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbc.connectionURL=jdbc:sqlserver://localhost:1433;DatabaseName=ssmbase
#jdbc.username=LOUIS
#jdbc.password=123456

#MySql database
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://localhost:3306/ssmbase?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

4、在配置applicationContext.xml檔案時,引入了mybaties的全域性配置檔案,Mybaties全域性配置檔案如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
   <settings>
      <!-- 這個配置使全域性的對映器啟用或禁用快取 -->
      <setting name="cacheEnabled" value="true" />
      <!-- 允許 JDBC 支援生成的鍵。需要適合的驅動。如果設定為 true 則這個設定強制生成的鍵被使用,儘管一些驅動拒絕相容但仍然有效(比如 Derby) -->
      <setting name="useGeneratedKeys" value="true" />
      <!-- 配置預設的執行器。SIMPLE 執行器沒有什麼特別之處。REUSE 執行器重用預處理語句。BATCH 執行器重用語句和批量更新 -->
      <setting name="defaultExecutorType" value="REUSE" />
      
      <setting name="jdbcTypeForNull" value="NULL" />
      
      <!-- 設定超時時間,它決定驅動等待一個數據庫響應的時間。 -->
      <setting name="defaultStatementTimeout" value="25000" />
      <!-- 配置打印出日誌的,感覺沒什麼用 -->
      <setting name="logImpl" value="LOG4J" />
        <setting name="logImpl" value="STDOUT_LOGGING" />
      <!-- 開啟延遲載入 -->
      <setting name="lazyLoadingEnabled" value="true" />
      <setting name="aggressiveLazyLoading" value="false" />
        <setting name="callSettersOnNulls" value="true"/>     
   </settings>

</configuration>

5、配置好maven庫、spring核心檔案,接下來配置springmvc 的檢視解析檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
   <!-- 配置SpringMVC -->
   <!-- 1.開啟SpringMVC註解模式 -->
   <!-- 簡化配置: 
      (1)自動註冊DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
      (2)提供一些列:資料繫結,數字和日期的format @NumberFormat, @DateTimeFormat, xml,json預設讀寫支援 
   -->
   <mvc:annotation-driven />

   <!-- use-default-filters="false" 只掃描指定的註解 -->
   <context:component-scan base-package="com.ssm.controller" >
      <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
      <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
   </context:component-scan>

   <aop:aspectj-autoproxy proxy-target-class="true"/>
   
   <!-- 2.靜態資源預設servlet配置
      (1)加入對靜態資源的處理:js,gif,png
      (2)允許使用"/"做整體對映
    -->
    <mvc:default-servlet-handler/>
    
    <!-- 3.配置jsp 顯示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.掃描web相關的bean -->
    <context:component-scan base-package="com.ssm.controller" />

    <!-- 5.檔案上傳需要的配置-->
   <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      <property name="maxUploadSize" value="512000000"/>
   </bean>
</beans>

6、配置日誌檔案

#log4j.logger.org.hibernate.tool.hbm2ddl=debug
log4j.rootLogger=info,Console,R
log4j.addivity.org.apache=true
log4j.logger.com.zhiyin.mes.log.normal=debug,R
log4j.logger.com.zhiyin.mes.log.debug=debug,Console

log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${MySSM.root}/../logs/MySSM.log
log4j.appender.R.Encoding=utf-8
log4j.appender.R.MaxFileSize=20MB 
log4j.appender.R.Append=true 
log4j.appender.R.MaxBackupIndex=108 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%d %-5p [%t][%C %L] %m%n

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
#log4j.appender.Console.layout.ConversionPattern=ConSole: %d [%t] %-5p [%c] - %m%n
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%C %L] - %m%n
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout

#log4j.logger.org.apache=ERROR 
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement =DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
#log4j.logger.java.sql.ResultSet = ERROR
 
 log4j.logger.org.hibernate=INFO
 #log4j.logger.org.hibernate.hql.ast.AST=ERROR
 #log4j.logger.org.hibernate.SQL=ERROR
 #log4j.logger.org.hibernate.type=ERROR
 #log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=ERROR
 #log4j.logger.org.hibernate.hql=ERROR
 #log4j.logger.org.hibernate.cache=ERROR
 #log4j.logger.org.hibernate.transaction=ERROR
 #log4j.logger.org.hibernate.jdbc=ERROR
 #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=ERROR
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG 
#log4j.logger.com.zhiyin.dao = TRACE
log4j.logger.com.zhiyin.dao = INFO

7、最後一步配置web.xml檔案,該檔案用於載入spring的監聽,過濾字元等一系列在初始化時就要觸發的操作。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

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

    <!-- 配置log日誌 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>MySSM.root</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!--Spring 監聽 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 字元過濾-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

整個配置到此就結束,接下來,針對以上配置進行一些操作,用於驗證配置是否正確。

三、實現通用的增刪改查方法

1、全域性意識

        我們在進行編碼之前,首先需要想到,是不是有些程式碼可以重用?是否可以提取一些公用的東西,不管是這個專案還是以後得專案都可以使用?我們是否要考慮資料的完整性?等等,都是我們需要在開始寫程式碼之前考慮的問題。如果之前沒有考慮好,等進行一段時間的編碼過後,再想到提取,那樣只會浪費時間。因此,在這個專案結構中,不管是service還是dao,或者是controller,我都先設計了Base*這一層,在我們需要實現業務邏輯時,繼承base類,則可以省去很多的功夫。

2、IBaseDao.java 和其所對應的BaseMapper.xml

    IBaseDao.java檔案

package com.ssm.dao.base;

import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface IBaseDao {

    /** 插入方法 **/
    int insert(Map map);

    /** 更新方法 **/
    int update(Map map);

    /** 通過id 查詢對應資料 **/
    Map findById(@Param("tablename") String tableName, @Param("id") Integer id);

    /** 獲取所有記錄 **/
    List<Map> findAll(@Param("tablename")String tableName,@Param("issoftdel")String isSoftDel);

    /** 硬刪除,刪除後資料庫記錄消失  **/
    int deleteById(@Param("tablename")String tableName,@Param("id")Integer id);

    /** 軟刪除,更新是否刪除標記  **/
    int deleteSoftById(@Param("tablename")String tableName,@Param("id")Integer id);

    /** 通過條件查詢資料,用於校驗是否重複 **/
    List<Map> findByCondition(Map params);

    /** 通過表名獲取下一個id **/
    int findNextId(@Param("tablename")String tableName);
}

對應的BaseMapper.xml 檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "classpath://mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.dao.base.IBaseDao">

    <insert id="insert" parameterType="Map" keyProperty="id">
        insert into ${tablename}
        <foreach collection="fields" index="key" item="val" separator="," open="(" close=")">
            ${key}
        </foreach>
        values
        <foreach collection="fields" index="key" item="val" separator="," open="(" close=")">
            <if test=" key== 'id'">
                ${val}
            </if>
            <if test=" key != 'id'">
                #{val}
            </if>
        </foreach>
    </insert>

    <update id="update" parameterType="Map">
        update ${tablename} set
        <foreach collection="fields" index="key" item="val" separator=",">
            <if test=" key != null and key !='id'">${key}=#{val}</if>
        </foreach>
        where id = ${id}
    </update>

    <select id="findById" resultType="Map" parameterType="Map">
        select * from ${tablename} where id = #{id}
    </select>

    <select id="findAll" resultType="Map" parameterType="Map">
        select a.* from ${tablename} a
        where 1 =1
        <if test="issoftdel != null and issoftdel != '' and issoftdel == 'false'">
            and a.delflag != 1
        </if>
    </select>

    <delete id="deleteById" parameterType="Map">
        delete from ${tablename} where id = #{id}
    </delete>

    <update id="deleteSoftById" parameterType="Map">
        update ${tablename} set delflag = 1
        where id = #{id}
    </update>

    <select id="findByCondition" resultType="Map" parameterType="Map">
        select * from ${tablename} a
            where a.${code} = #{value}
        <if test="issoftdel != null and issoftdel != '' and issoftdel =='false'">
            and a.delflag != 1
        </if>
    </select>

    <select id="findNextId" parameterType="Map" resultType="int">
        select ifnull(max(id),0)+1 from ${tablename}
    </select>

</mapper>

        在這裡,我對於增刪改查進行了統一的封裝,其中有一點需要說明的是,我設計的資料庫每一個基表都會有一個DelFlag欄位,這個欄位的作用在於我們刪除的時候,決定是否是真正的刪除(軟刪除和硬刪除),即是否真正的從資料庫中將記錄刪除掉。如果是真正的刪除,則無法重新找回相應的記錄,軟刪除的效果在於,如果何時,記錄都在,只是有一個標記標記它這條記錄是否應該被查詢或者被校驗。

2、BaseService.java

package com.ssm.service.base;

import com.ssm.dao.base.IBaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BaseService {

    @Autowired
    private IBaseDao iBaseDao;


    /***
     *  插入方法
     * @param cls bean class
     * @param beanObj bean 物件
     * @param tableName 表名
     * @return int
     * @throws Exception 異常
     */
    public int insertSimple(Class cls, Object beanObj, String tableName){
        Map<String,Object> para = new HashMap<String,Object>();
        this.buildBeanAttrPara(cls, beanObj, para);
        para.put("tablename", tableName);
        return iBaseDao.insert(para);
    }

    /***
     *  更新方法
     * @param cls bean class
     * @param fromObj bean 物件
     * @param toObj bean 物件
     * @param tableName 表名
     * @return int
     * @throws Exception 異常
     */
    public int updateSimple(Class cls, Object fromObj, Object toObj, String tableName, Object id) throws Exception {
        this.assignBeanAttrPara(cls, fromObj, toObj);
        Map para = new HashMap();
        para.put("id", id);
        this.buildBeanAttrPara(cls, toObj, para);
        para.put("tablename", tableName);
        return this.iBaseDao.update(para);
    }

    /**
     *  通過Id 查詢資料
     * @param tableName 表名
     * @param id id
     * @return map
     */
    public Map findById(String tableName,Integer id){
        return iBaseDao.findById(tableName,id);
    }

    /**
     *  查詢表中所有的資料
     * @param tableName 表名
     * @param isSoftDel 是否包含軟刪除,true:包含,false:不包含
     * @return list
     */
    public List<Map> findAll(String tableName,boolean isSoftDel){

        return iBaseDao.findAll(tableName,Boolean.toString(isSoftDel));
    }

    /**
     *  通過id刪除資料
     * @param tableName 表名
     * @param id id
     * @param isSoftDel 是否是軟刪除
     * @return int
     */
    public int deleteById(String tableName,Integer id,boolean isSoftDel){
        if(isSoftDel){
            return iBaseDao.deleteSoftById(tableName,id);
        }else{
            return iBaseDao.deleteById(tableName,id);
        }
    }

    /***
     *  校驗在table中是否存在重複記錄
     * @param tableName 需要校驗的記錄表
     * @param condition 表字段
     * @param value 值
     * @param isSoftDel 是否校驗軟刪除,true:包含軟刪除,false:不包含軟刪除
     * @return boolean ,true:重複,false:未重複
     */
    public boolean checkIsDuplicate(String tableName,String condition,String value,boolean isSoftDel){
        Map<String,String> map = new HashMap<String, String>();
        map.put("tablename",tableName);
        map.put("condition",condition);
        map.put("value",value);
        map.put("issoftdel",String.valueOf(isSoftDel));
        List<Map> list = iBaseDao.findByCondition(map);
        if(list.size() >0 ){
            return true;
        }else{
            return false;
        }
    }

    public int getId(String tableName){
        return iBaseDao.findNextId(tableName);
    }

    /**
     * 將一個 Map 物件轉化為一個 JavaBean
     * @param type 要轉化的型別
     * @param map 包含屬性值的 map
     * @return 轉化出來的 JavaBean 物件
     * @throws IntrospectionException 如果分析類屬性失敗
     * @throws IllegalAccessException 如果例項化 JavaBean 失敗
     * @throws InstantiationException 如果例項化 JavaBean 失敗
     * @throws InvocationTargetException 如果呼叫屬性的 setter 方法失敗
     */
    @SuppressWarnings("rawtypes")
    public static Object convertFromMap(Class type, Map map)
            throws IntrospectionException, IllegalAccessException,
            InstantiationException, InvocationTargetException
    {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);         // 獲取類屬性
        Object obj = type.newInstance();                            // 建立 JavaBean 物件

        // 給 JavaBean 物件的屬性賦值
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (int i = 0; i< propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            Class propType = descriptor.getPropertyType();
            if (map.containsKey(propertyName.toLowerCase())) {
                // 下面一句可以 try 起來,這樣當一個屬性賦值失敗的時候就不會影響其他屬性賦值。
                Object value = map.get(propertyName.toLowerCase());

                if (value.equals(""))
                    continue;

                Class valType = value.getClass();
                if (valType.equals(BigDecimal.class) && (propType.equals(Integer.class) || propType.equals(int.class))) {
                    value = Integer.parseInt(value.toString());
                }
                if (valType.equals(String.class) && (propType.equals(Integer.class) || propType.equals(int.class))) {
                    value = Integer.parseInt(value.toString());
                }
                if (valType.equals(String.class) && (propType.equals(Double.class) || propType.equals(double.class))) {
                    value = Double.parseDouble(value.toString());
                }

                Object[] args = new Object[1];
                args[0] = value;

                descriptor.getWriteMethod().invoke(obj, args);
            }
        }
        return obj;
    }

    /***
     *  將bean轉換成map,用於儲存資料到資料庫
     * @param cls bean class
     * @param obj bean 物件
     * @param para map
     * @throws Exception 異常
     */
    public void buildBeanAttrPara(Class cls, Object obj, Map para){
        Field[] fields = cls.getDeclaredFields();
        Field.setAccessible(fields, true);
        Map<String,Object> keyVal = new HashMap();
        Field[] var9 = fields;
        int var8 = fields.length;
        try {
            for(int var7 = 0; var7 < var8; ++var7) {
                Field field = var9[var7];
                keyVal.put(field.getName().toLowerCase(), field.get(obj));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        para.put("fields", keyVal);
    }

    public void assignBeanAttrPara(Class cls, Object from, Object to) throws Exception {
        Field[] fields = cls.getDeclaredFields();
        Field.setAccessible(fields, true);
        new HashMap();
        Field[] var9 = fields;
        int var8 = fields.length;

        for(int var7 = 0; var7 < var8; ++var7) {
            Field field = var9[var7];
            Object val = field.get(from);
            if (val != null) {
                field.set(to, val);
            }
        }

    }
}

        程式碼部分有詳細的註釋,這裡需要說明的是 插入和更新 這兩個方法。我們利用javabean 和map的轉換關係,實現通用的插入和更新的方法。因此,我們在插入或者更新時,都會依賴於javabean 物件,如果在我們得javabean中,沒有將資料庫中的欄位寫全,即實體類與表結構對應不上,將會丟擲異常。

        實現插入的具體思想是,通過獲取Class的屬性,和屬性對應的值,進行map的建立,對應到mapper中,迴圈所有的物件屬性,拼接插入的sql 語句,從而達到目的。

3、BaseController.java實現

package com.ssm.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class BaseController {

    public static Map getParameterMap(HttpServletRequest request) {
        Map properties = request.getParameterMap();
        Map<String,Object> returnMap = new HashMap<String, Object>();
        Iterator entries = properties.entrySet().iterator();
        String name = "";
        String value = "";
        while(entries.hasNext()) {
            Map.Entry entry = (Map.Entry)entries.next();
            name = (String)entry.getKey();
            Object valueObj = entry.getValue();
            if (valueObj == null) {
                value = "";
            } else if (!(valueObj instanceof String[])) {
                value = valueObj.toString();
            } else {
                value = "";
                String[] values = (String[])valueObj;
                for (String v :values) {
                    value = value + v +",";
                }
                value = value.substring(0, value.length() - 1);
            }
            value = value.trim();
            returnMap.put(name, value);
        }
        return returnMap;
    }
}

        在這裡,我只將通過request獲取引數並返回Map的方法提取出來,這樣在具體的業務Controller中就可以直接通過該方法拿到一個Map型別的引數列表,實現簡便化。

四、實現使用者的增刪改查操作

1、資料庫表

CREATE TABLE IF NOT EXISTS `sys_user`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `name` VARCHAR(40) NOT NULL,
   `password` VARCHAR(40) NOT NULL,
   `phone` VARCHAR(11) NULL,
   `delFlag` int default 0,
   PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、User.java 對應的bean檔案

package com.ssm.bean;

import java.io.Serializable;

public class User implements Serializable{

    private Integer id;
    private String name;
    private String password;
    private String phone;
    private Integer delFlag = 0;

    public User() {
    }

    public User(Integer id, String name, String password, String phone,Integer delFlag) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.phone = phone;
        this.delFlag = delFlag;
    }

    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;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Integer getDelFlag() {
        return delFlag;
    }

    public void setDelFlag(Integer delFlag) {
        this.delFlag = delFlag;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", delFlag=" + delFlag +
                '}';
    }
}

3、UserService.java

package com.ssm.service.user;

import com.ssm.bean.User;
import com.ssm.dao.user.IUserDao;
import com.ssm.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService extends BaseService{

    private static final String tableName = "sys_user";

    @Autowired
    private IUserDao iUserDao;

    /***
     *  儲存User資訊
     * @param user user
     * @return Map
     */
    public Map saveUser(User user){
        // 通過手動獲取id 的方法設定id
        user.setId(getId(tableName));
        // 插入資料庫
        int affected = insertSimple(User.class,user,tableName);
        // 組織返回資料(此處可以設計一個用於返回的實體)
        Map<String,Object> map = new HashMap<>();
        if(affected == 1){
            map.put("message","新增成功");
            map.put("successful",1);
        }else{
            map.put("message","新增失敗");
            map.put("successful",0);
        }
        return map;
    }

    /***
     *  儲存User資訊
     * @param id id
     * @return Map
     */
    public Map deleteUser(int id ){
        // 刪除使用者資訊,第三個引數為 isSoftDel,代表軟硬刪除
        int affected = deleteById(tableName,id,true);
        // 組織返回資料(此處可以設計一個用於返回的實體)
        Map<String,Object> map = new HashMap<>();
        if(affected == 0) {
            map.put("message","要刪除的使用者不存在");
            map.put("successful",0);
        }else{
            map.put("message","刪除成功");
            map.put("successful",1);
        }
        return map;
    }

    public List<Map> queryAllUsers(Map params) throws Exception{
        return findAll(tableName,false);
    }
}

4、UserController.java

package com.ssm.controller.user;


import com.alibaba.fastjson.JSONObject;
import com.ssm.bean.User;
import com.ssm.controller.BaseController;
import com.ssm.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/SsmRoot/User")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/saveUser",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String saveUser(HttpServletRequest request, HttpServletResponse response) throws Exception{
        JSONObject jsonObject = new JSONObject();
        User user = new User();
        user.setName("test");
        user.setPassword("test");
        user.setPhone("13122225555");
        return jsonObject.toJSONString(userService.saveUser(user));
    }

    @RequestMapping(value = "/deleteUser",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception{
        JSONObject jsonObject = new JSONObject();

        int id = 1;
        return jsonObject.toJSONString(userService.deleteUser(id));
    }

    @RequestMapping(value = "/queryAllUses",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String queryAllUsers(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Map params = getParameterMap(request);
        JSONObject jsonObject = new JSONObject();
        return jsonObject.toJSONString(userService.queryAllUsers(params));
    }
}

5、index.jsp

<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2018/3/31
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
  <script type="text/javascript" src="<%=request.getContextPath()%>/tools/jquery/jquery.min.js"></script>

  <script>
      function onSave() {
          $.post("../SsmRoot/User/saveUser",{},function (data) {
              console.log(data);
              $("#text").html(data);
          })
      }
      function onDelete() {
          $.post("../SsmRoot/User/deleteUser",{},function (data) {
              console.log(data);
              $("#text").html(data);
          })
      }
      function onQuery() {
          $.post("../SsmRoot/User/queryAllUses",{},function (data) {
              console.log(data);
              $("#text").html(data);
          })
      }
  </script>
</head>
<body>
  <input type="button" onclick="onSave()" name="增加" value="增加">
  <input type="button" onclick="onDelete()" name="刪除" value="刪除">
  <input type="button" onclick="onQuery()" name="請求" value="查詢所有資料">

  <br/>
  <br/>
  <br/>
  <br/>
  <textarea name="text" id="text" cols="90" rows="30"></textarea>"
  </body>
</html>

五、驗證

1、驗證增加

初始查詢資料庫結果為0行。

點選增加按鈕兩次:

可以看到已經有兩條資料產生。

2、驗證查詢資料

點選查詢所有資料按鈕,查詢結果如上所示。

3、驗證刪除

點選刪除後,再次查詢資料,只有一條結果。

查詢資料庫:

可以看到這裡用的是軟刪除標記,資料庫中仍有兩條資料。

六、總結

       作為一個開發人員,首先應該有一個全域性的把握,否則會給自己找來很多不必要的麻煩。

其次,關於框架的條條框框不是靠死記硬背,只有理解了其中的奧祕,才能遇到問題迎刃而解。

最後,祝大家學習愉快。

程式碼已經上傳到csdn,如有需要請下載:MySSM