SSM整合_年轻人的第一个增删改查_基础环境搭建

写在前面

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
posted @ 2022-04-12 18:54  蔚然丶丶  阅读(599)  评论(4编辑  收藏  举报