SSM整合_年輕人的第一個增刪改查_基礎環境搭建

蔚然丶丶發表於2022-04-12

寫在前面

SSM整合_年輕人的第一個增刪改查_基礎環境搭建
SSM整合_年輕人的第一個增刪改查_查詢
SSM整合_年輕人的第一個增刪改查_新增
SSM整合_年輕人的第一個增刪改查_修改
SSM整合_年輕人的第一個增刪改查_刪除
GitHub:https://github.com/say-hey/ssm_crud
Gitee:https://gitee.com/say-hey/ssm_crud

  有用嗎?對於學完Spring、SpringMVC、Mybatis還無從下手的同學來說這是一個很好引子。對於正在學習同一個案例的同學,可能解決一些問題。對於需要這個案例的同學可以直接獲取。

  有什麼?xml配置檔案編寫,引入一個簡單的前端框架,使用MyBatis Generator逆向工程生成一些程式碼,使用框架簡單快速搭建一個頁面,好用的分頁工具PageHelper,簡單的前後端分離,傳送ajax請求,利用json傳遞資料,增、刪、改、查的簡單實現。

  簡單嗎?內容很簡單,涉及Java程式碼不多,但是對於新手來說,最困難的部分是各種環境搭建、配置檔案、版本衝突,如果能夠根據錯誤提示動手解決,那就是一大進步。

  怎麼學?如果有時間可以在B站搜尋:ssm整合crud,雷豐陽講的。如果想看到每個功能的實現過程和原始碼,可以在這裡學習,每個步驟都有註釋。也可以作為複習快速瀏覽。

  什麼樣?如下圖:

image
image
image
image
image
image

1、基礎環境搭建

  1. 安裝設定java、maven、mysql
  2. 設定編輯器UTF-8,Tomcat編碼UTF-8
  3. 待補充

1. 建立Maven工程

  • 不同編譯器建立工程稍有不同,大致目錄結構
ssm_crud
    src
        main
        	java
        	resources
        	webapp
                WEB-INF
                	views
                	web.xml
                index.jsp
	pom.xml

2. 引入依賴jar

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>ssm_crud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ssm_crud Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <!-- 引入jar包 -->
    <!-- spring,springmvc,mybatis,資料庫連線池c3p0,資料庫驅動包 -->
    <dependencies>
        <!-- spring-webmvc 包含spring和springmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- spring資料庫驅動 spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- spring面向切面程式設計 spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- spring 單元測試 -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.1.RELEASE</version>
            <scope>provided</scope>
        </dependency>

        <!-- MyBatis -->
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!-- spring和mybatis整合 mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>

        <!-- 資料庫連線池 驅動,兩個資料來源配置名不同,需要注意 -->
        <!-- c3p0資料來源 -->
        <!--老版 <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version> </dependency> -->
        <!--    <dependency>-->
        <!--      <groupId>com.mchange</groupId>-->
        <!--      <artifactId>c3p0</artifactId>-->
        <!--      <version>0.9.5.5</version>-->
        <!--    </dependency>-->

        <!--  druid資料來源  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!-- mysql-connector-java 注意:要和MySQL統一版本,MySQL5,MySQL8 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--     8.0.21       -->
            <version>8.0.18</version>
        </dependency>

        <!-- web專案其他包(jstl,servlet-api,junit) -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- Servlet api 是執行時需要,伺服器中有,不需要打包,就配置<scope>provided</scope> -->
        <!-- servlet-api是3.0之前版本,java.servlet-api是3.0之後版本 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- junit4測試-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- junit5測試-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <!--  idea建立maven專案自動生成  -->
    <build>
        <finalName>ssm_crud</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

3. 引入Bootstrap前端框架

  • Bootstrap官網下載:起步 · Bootstrap v3 中文文件 | Bootstrap 中文網 (bootcss.com)

  • webapp目錄下建立static目錄,將bootstrap-3.3.7-dist整個資料夾放入

  • 在static目錄下引入jquery-1.12.4.js檔案

  • 在webapp目錄下的index.jsp中使用,只需要檢視文件新增相應的class樣式

    ssm_crud
        src
            main
            	java
            	resources
                webapp
                	static
                		bootstrap-3.3.7-dist
                		jquery-1.12.4.js
                    WEB-INF
                    	views
                        web.xml
                    index.jsp
    	pom.xml
    
    <%-- 解決亂碼 --%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <head>
        <script src="static/jquery-1.12.4.js"></script>
        <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
        <link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <h2>Hello World!</h2>
        <button type="button" class="btn btn-primary">(首選項)Primary</button>
    </body>
    </html>
    
  • index.jsp在Tomcat中執行

  • 根據Tomcat設定埠訪問http://localhost:[埠號]/index.jsp

  • 會出現帶有Bootstrap樣式的按鈕

4. SSM整合配置檔案

  • 配置檔案是到目前為止,後續使用功能再新增
  • 雖然後面SpringBoot、SpringCloud配置檔案變少了,但配置檔案有助於理解框架的結構和功能
  • 使用不同Spring版本,部分配置檔案可能不同,下面是Spring 5

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <!--  標籤按順序編寫  -->
    <display-name>Archetype Created Web Application</display-name>
    <!-- 1.啟動spring的容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 2.字元編碼過濾器 ,放在最前面執行-->
    <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>
        <!-- 設定響應和請求格式都為true -->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>


    <!-- 3.使用REST風格URI,將普通的POST請求轉為DELETE,GET -->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <!-- 新增能直接處理PUT請求的過濾器 -->
    <!-- HttpPutFormContentFilter過時了,使用 FormContentFilter能支援PUT和DELETE-->
    <filter>
        <filter-name>formContentFilter</filter-name>
        <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>formContentFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 4.監聽器,專案啟動指定載入某spring配置檔案,用於初始化 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 5.SpringMVC前端控制器, 攔截所有請求-->
    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 指定springmvc配置檔案 -->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- spring配置檔案,主要配置業務邏輯有關 -->
    <!-- 資料來源,事務控制,mybatis整合 -->

    <!-- 自動掃描元件,但是不掃描Controller,Controller讓springmvc掃描 -->
    <context:component-scan base-package="com.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <!-- 引入外部配置檔案 -->
    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <!-- 資料來源 C3P0 -->
    <!--    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!--        <property name="driverClass" value="${jdbc.driver}"/>-->
    <!--        <property name="jdbcUrl" value="${jdbc.url}"/>-->
    <!--        <property name="user" value="${jdbc.user}"/>-->
    <!--        <property name="password" value="${jdbc.password}"/>-->
    <!--    </bean>-->
    <!--  druid資料來源  -->
    <bean id="pooledDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.jdbcUrl}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置mybatis整合 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全域性配置檔案 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 資料來源 -->
        <property name="dataSource" ref="pooledDataSource"/>
        <!-- 指定mybatis,mapper檔案位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!-- 配置掃描器,將mybatis介面的實現加入到IOC容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 掃描所有dao介面實現,加入IOC容器中 -->
        <property name="basePackage" value="com.ssm.dao"></property>
    </bean>

    <!-- 配置一個可以執行批量sqlSession -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
        <!-- 使用批量執行器 -->
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>

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

    <!-- 開啟基於註解/xml的事務,重要的用xml配合 -->
    <aop:config>
        <!-- 切入點表示式 被匹配中的都是切入點 之後被事務增強-->
        <aop:pointcut expression="execution(* com.ssm.service..*(..))" id="txPoint"/>
        <!-- 配置事務增強 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>

    <!-- 利用事務管理器transactionManager,將上下兩個配置連結一起,利用切入點表示式進行切入,之後的方法看下面 -->
    <!-- 配置事務增強 事務如何切入--><!-- 切入點表示式之後怎麼切,要看下面的方法 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- * 代表所有方法都是事務方法 -->
            <tx:method name="*"/>
            <!-- 以get開頭的方法 read-only只讀-->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>

dbconfig.properties

#c3p0資料來源配置,使用jdbc字首防止衝突
#jdbc.driver=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
#jdbc.user=root
#jdbc.password=123456

#druid資料來源配置,mysql 5和mysql 8配置資訊不同
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456

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>
    <settings>
        <!-- 駝峰命名規則 從經典資料庫列名 A_COLUMN 到經典 Java 屬性名 aColumn 的類似對映。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.ssm.bean"/>
    </typeAliases>
</configuration>

springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- SpringMVC配置檔案:包含網站跳轉 -->
    <!-- 自動掃描元件,檢視解析器,兩個mvc標準配置 -->

    <!-- 自動掃描元件 ***-->
    <context:component-scan base-package="com.ssm" use-default-filters="false">
        <!-- use-default-filters="false" 禁用預設掃描包 -->
        <!-- 所以一般做法是,在SpringMVC的配置裡,只掃描Controller層,
                Spring配置 中掃描所有包,但是排除Controller層。 -->
        <!-- include-filter 只掃描指定註解類 -->
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 兩個標準配置 -->
    <!-- 將springmvc不能處理的請求交給Tomcat  靜態頁面,如html,css,js,images可以訪問-->
    <mvc:default-servlet-handler/>
    <!-- 支援springmvc更高階功能,如JSR03校驗,快捷ajax請求...對映動態請求
    註解驅動,以使得訪問路徑與方法的匹配可以通過註解配置-->
    <mvc:annotation-driven/>
</beans>

5. 建立資料庫

  • 一個庫ssm_crud,兩個表tbl_depttbl_emp
-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept`  (
  `dept_id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`dept_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Table structure for tbl_emp
-- ----------------------------
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp`  (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `d_id` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`emp_id`) USING BTREE,
  INDEX `fk_emp_dept`(`d_id`) USING BTREE,
  CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1036 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

6. MyBatis Generator逆向工程

逆向生成

  • 根據現有的資料庫結構生成物件的JavaBean、Dao介面、Mapper.xml等

  • 在ssm_crud根目錄下建立mbg.xml配置檔案

    <?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="DB2Tables" targetRuntime="MyBatis3">
    
            <!-- 生成toString方法-->
            <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
    
            <!-- 禁止自動生成註釋 -->
            <commentGenerator>
                <!-- 編碼格式 -->
                <property name="javaFileEncoding" value="UTF-8"/>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
    
            <!-- 配置資料庫連線 -->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&amp;useSSL=false"
                            userId="root" password="123456"/>
    
            <!--資料庫BigDecimals欄位在java中定義 -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
            <!-- 指定JavaBean生成位置 -->
            <javaModelGenerator targetPackage="com.ssm.bean"
                                targetProject="src\main\java"/>
    
            <!-- 指定sql對映檔案生產位置 -->
            <sqlMapGenerator targetPackage="mapper"
                             targetProject="src\main\resources"/>
    
            <!-- 指定dao介面生成的位置,mapper介面 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="com.ssm.dao" targetProject="src\main\java"/>
    
            <!-- 指定每個表生成策略 -->
            <table tableName="tbl_emp" domainObjectName="Employee"></table>
            <table tableName="tbl_dept" domainObjectName="Department"></table>
    
        </context>
    </generatorConfiguration>
    
  • com.ssm.test包中任意建立一個測試方法,然後執行

    /**
     * MyBatis Generator逆向工程
     */
    public class MBGTest {
        public static void main(String[] args) throws InvalidConfigurationException, IOException, XMLParserException, SQLException, InterruptedException {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            File configFile = new File("mbg.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
        }
    
    }
    
  • 之後專案自動生成檔案,主要分三部分

    • 每個表生成對應JavaBean和對應的查詢條件Example
    • Dao介面
    • Mapper.xml檔案

聯表查詢

  • 自動生成的功能不能滿足指定的查詢條件,所以需要修改

  • 實現一條sql完成聯表查詢,在逆向工程的基礎上,需要修改以下地方

  • JavaBean

    • Department

      package com.ssm.bean;
      
      public class Department {
          private Integer deptId;
      
          private String deptName;
      
          //如果用了構造器,一定要寫無參構造器
          public Department() {
              super();
          }
          public Department(Integer deptId, String deptName) {
              super();
              this.deptId = deptId;
              this.deptName = deptName;
          }
      
          //get/set/toString
      }
      
    • Employee

      package com.ssm.bean;
      
      public class Employee {
          private Integer empId;
      
          private String empName;
      
          private String gender;
      
          private String email;
      
          private Integer dId;
      
          // 增加聯合查詢
          private Department department;
          // 如果用了構造器,一定要寫無參構造器
          public Employee() {
              super();
          }
          // 不加Department的屬性
          public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
              super();
              this.empId = empId;
              this.empName = empName;
              this.gender = gender;
              this.email = email;
              this.dId = dId;
          }
      
          // get/set/toString
      }
      
  • Dao

    • EmployeeMapper

      public interface EmployeeMapper {
      	//...
      	
      	//新增兩個查詢方法,用於聯合查詢
          List<Employee> selectByExampleWithDept(EmployeeExample example);
          Employee selectByPrimaryKeyWithDept(Integer empId);
      }
      
  • Mapper

    • EmployeeMapper.xml

      <mapper namespace="com.ssm.dao.EmployeeMapper">
      	<!-- ... -->
      	
          <!-- 新增兩個查詢方法,在查empt員工時,同時查出部門聯合查詢 -->
          <!-- 條件查詢  List<Employee> selectByExampleWithDept(EmployeeExample example); -->
          <!-- 查詢主鍵  Employee selectByPrimaryKeyWithDept(Integer empId); -->
      
          <!-- 新增  查詢empty和dept的列 -->
          <sql id="WithDept_Column_List">
        	e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
          </sql>
          <!-- 新增 處理自定義的返回對映 部門資訊封裝-->
          <resultMap type="com.ssm.bean.Employee" id="WithDeptResultMap">
              <id column="emp_id" jdbcType="INTEGER" property="empId" />
              <result column="emp_name" jdbcType="VARCHAR" property="empName" />
              <result column="gender" jdbcType="CHAR" property="gender" />
              <result column="email" jdbcType="VARCHAR" property="email" />
              <result column="d_id" jdbcType="INTEGER" property="dId" />
              <!-- 聯合查詢 部門資訊封裝 -->
              <association property="department" javaType="com.ssm.bean.Department">
                  <id column="dept_id" property="deptId"/>
                  <result column="dept_name" property="deptName"/>
              </association>
          </resultMap>
      
          <!-- 自定義 根據條件查詢 聯表 員工+部門 按照逆向模板修改-->
          <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
              select
              <if test="distinct">
                  distinct
              </if>
              <!-- 查詢條件,只用自定義的,包含兩個表的欄位 -->
              <include refid="WithDept_Column_List"/>
              from tbl_emp e
              left join tbl_dept d
              on e.d_id = d.dept_id
              <!-- 後面語句用來處理條件 -->
              <if test="_parameter != null">
                  <include refid="Example_Where_Clause"/>
              </if>
              <!-- 原裝,應該是複雜查詢中的排序條件
              <if test="orderByClause != null">
                order by ${orderByClause}
              </if> -->
              order by e.emp_id
          </select>
          <!-- 自定義 根據主鍵查詢 聯表 員工+部門 -->
          <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
              select
              <include refid="WithDept_Column_List"/>
              from tbl_emp e
              left join tbl_dept d
              on e.d_id = d.dept_id
              where emp_id = #{empId,jdbcType=INTEGER}
          </select>
          
      	<!-- ... -->
      </mapper>
      

批量插入

  • com.ssm.test中任意建立測試類,測試sql連線並新增資料

    //如果您想在測試中使用Spring測試框架功能(例如)@MockBean,則必須使用@ExtendWith(SpringExtension.class)。它取代了不推薦使用的JUnit4@RunWith(SpringJUnit4ClassRunner.class)
    @ExtendWith(SpringExtension.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class MapperTest {
    
    	@Autowired
    	DepartmentMapper departmentMapper;
    	@Autowired
    	EmployeeMapper employeeMapper;
    	//批量sqlSession
    	@Autowired
    	SqlSessionTemplate sqlSessionTemplate;
    
        @Test
        public void test(){
            //Employee employee = employeeMapper.selectByPrimaryKeyWithDept(1);
            //System.out.println(employee);
            
            //1.插入部門
    //		departmentMapper.insertSelective(new Department(null, "開發部"));
    //		departmentMapper.insertSelective(new Department(null, "測試部"));
    		
    		//2.插入員工
    //		employeeMapper.insertSelective(new Employee(null, "Tom", "M", "Tom@123.com", 1));
    		
    		//3.批量插入
    		//使用sqlSessionTemplat可以實現批量,不使用就不是
    		EmployeeMapper eMapperTemplat = sqlSessionTemplate.getMapper(EmployeeMapper.class);
    		for(int i = 0 ; i <= 1000 ; i++) {
    			
    			String uuid = UUID.randomUUID().toString().substring(0, 5) + i;
    			//這裡繼續使用employeeMapper就不行
    			//employeeMapper.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
    			
    			//使用employeeMapperTemplat批量插入
    			eMapperTemplat.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
    		}
    	}
        
    }
    

7. 總結

到目前為止,Spring、SpringMVC、MyBatis都已經配置完成,各功能可以連通,可以進行編寫增刪改查的程式碼了。目前目錄結構如下

ssm_crud
    src
        main
        	java
        		com.ssm.bean
        			Department.java
        			EmployeeExample.java
        			Employee.java
        			DepartmentExample.java
        		com.ssm.dao
        			EmployeeMapper.java
        			DepartmentMapper.java
        		com.ssm.service
        		com.ssm.controller
        		com.ssm.test
        			MapperTest.java
        			MBGTest.java
        		com.ssm.utils
        	resources
        		mapper
        			DepartmentMapper.xml
        			EmployeeMapper.xml
        		applicationContext.xml
        		dbconfig.properties
        		mybatis-config.xml
        		springmvc.xml
            webapp
            	static
            		bootstrap-3.3.7-dist
        			jquery-1.12.4.js
                WEB-INF
                	views
                	web.xml
                index.jsp
	pom.xml
	mbg.xml

相關文章