SSM整合_实现增删改查_基础环境搭建

2023-05-16

写在前面

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,雷丰阳讲的。如果想看到每个功能的实现过程和源码,可以在这里学习,每个步骤都有注释。也可以作为复习快速浏览。

  什么样?如下图:

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

请添加图片描述

请添加图片描述

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SSM整合_实现增删改查_基础环境搭建 的相关文章

  • Android中锁定文件的方法

    androidSDK中并没有锁定文件相关的api 但是android是基于linux操作系统的 linux比较底层 灵活性也更大 为了实现锁定文件的效果 大概有以下几种办法 用chmod命令修改文件读写权限利用linux中的多线程独占锁 启
  • 远程控制Ubuntu

    远程控制Ubuntu 在Ubuntu上安装team viewer或者向日葵 xff0c 进行远程控制 xff0c 这里记录采用team viewer方式的配置过程 xff0c 向日葵等远程控制类似 安装Ubuntu 官方下载Ubuntu系统
  • 信号降噪方法

    傅里叶变换 只能获取一段信号总体上包含哪些频率的成分 xff0c 但是对各成分出现的时刻并无所知 对非平稳过程 xff0c 傅里叶变换有局限性 短时傅里叶变换 xff08 Short time Fourier Transform STFT
  • C++ 带通滤波

    Butterworth Filter Coefficients The following files are for a library of functions to calculate Butterworth filter coeff
  • python之collections

    collections是日常工作中的重点 高频模块 xff0c 包含了一些特殊的容器 xff0c 针对Python内置的容器 xff0c 例如list dict set和tuple xff0c 常用类型有 xff1a namedtuple
  • git 指定下载文件,目录

    1 创建路径 mkdir gitfile cd lt 路径 gt eg xff1a cd home gitfile 2 创建一个空的本地仓库 git init 3 连接远程仓库GitHub git remote add f origin l
  • Ubuntu v4l2 视屏流花屏问题

    之前用的好好解析YUV xff0c MJPEG 换了个核心板就不好使了 xff0c opencv3 4 6 gt gt gt opencv4 5 5 xff0c Mat xff0c cvMat xff0c IplImage 的类型转换也不好
  • qt qmake .qrc hasmodification time xxx in the future

    原因 xff1a 跨平台生成的 qrc 文件创建时间与目标平台时间不一致导致 xff0c 如win写的 copy 到 Linux xff0c 再编译可能会遇到该bug 导致无法qmake 与 build 解决 xff1a touch qrc
  • (转)python图像操作

    转自 xff1a zbxzc 侵删 使用PIL完成 python view plain copy span class hljs keyword import span Image span class hljs comment 打开图像
  • 关于input to reshape is a tensor 的问题

    span class hljs keyword for span index name span class hljs operator in span enumerate classes class path 61 cwd 43 name
  • mobileNet训练自己的样本

    span class hljs keyword import span matplotlib pyplot span class hljs keyword as span plt span class hljs keyword import
  • 关于屏幕适配之比例布局

    对于平板等需求场合 xff0c 它们的屏幕比例以16 xff1a 10和16 xff1a 9等为主 xff0c 但是屏幕尺寸各异 xff0c 分辨率各异 xff0c 即便是同一尺寸也有多种分辨率 xff0c 这种时候无论是使用dp还是px
  • 机器学习实战:ValueError: invalid literal for int() with base 10: '0.000000'

    在logistic回归一章中 xff0c 在将训练数据转换为int型时 xff0c 会出现日下报错 xff1a ValueError invalid literal for int with base 10 0 000000 只需将下面一句
  • cuda-8.0安装心得

    cuda 8 0安装 xff08 这两天不小心把原来的显卡驱动搞崩 xff0c 挣扎了好久 xff0c 只好重新走一遍 xff09 cuda 安装条件 gcc5 3 0 xff08 版本不能太高 xff09 sudo apt get ins
  • 在GPU刨过的坑

    这两天回学校这两天先是把自己的linux系统给强制删除了 xff0c 然后导致重启无法正常引导进入win xff0c 最后win也救不活了 xff0c 还不好重装系统 xff0c 各种文件损坏 xff0c 简单粗暴的翻车血泪史 捷径路上总是
  • [ArchLinux] 搜狗拼音输入法的安装

    配置源 在ArchlinuxCN源中有很多方便中国用户使用的包 xff0c 其中也包含了经常使用的搜狗拼音输入法 xff0c 于是我们需要先配置ArchlinuxCN源 xff0c 这样我们就可以使用自带的包管理器Pacman直接安装搜狗拼
  • [ArchLinux] 安装及KDE桌面环境安装配置

    ArchLinux 安装及KDE桌面环境安装配置 首先 xff0c 安装之前 xff0c 需要一个 启动介质 xff0c 我这里习惯使用USB设备作为启动介质 xff0c 这是由于ArchLinux滚动更新的特性 xff0c 而且占用空间很
  • 使用crontab执行定时任务时加flock独占锁防止进程堆积

    使用crontab执行定时任务 此处为每分钟执行一次 加flock独占锁防止进程堆积 注意给 var run 读写权限 xff0c 或者放到一个有读写权限的文件夹 span class token operator span span cl
  • macOs 安装liplpcap

    1 xff0c 下载liplpcap http www tcpdump org 1 在tcpdump网站下载libpcap的latest release 2 tar zxvf 3 configure make amp make instal
  • Android应用开发常用知识(4)

    Android string 中product的使用 Android的资源文件string xml会出现下面同名的字符串 xff1a lt string name 61 34 build type 34 product 61 34 tv 3

随机推荐

  • VR行业的发展现状和前景

    5G技术的应用推广 xff0c 加速推动虚拟现实不断发展和完善 xff0c VR产业迅速在各个领域和行业都得到广泛应用 xff0c 最好直观的感受就是知觉体验得到了良好的增强作用 本文的主要内容是简单概括VR技术的发展现状和发展前景 一 V
  • org.apache.ibatis.annotations不存在

    今天遇到了一个很有意思的bug 有人 xff08 还不止一个人 xff09 来问我 xff0c 为什么项目启动不了 xff0c 我说不可能啊 xff0c 我这不跑得好好的吗 xff0c 而且成功启动的也不止我一个啊 然后他就说 xff0c
  • 【学习笔记】Ubuntu双系统+搭建个人服务器

    Ubuntu双系统 43 搭建个人服务器 前言1 Ubuntu 43 Win双系统1 1 制作U盘启动盘1 2 系统分盘1 3 安装Ubuntu系统 2 搭建个人服务器2 1 设置root2 2 配置ssh2 3 向日葵连接 3 内网穿透3
  • (原创)开发微信公众平台遇到的乱码等问题的解决

    1 ngrok内网映射问题 首先这个工具是外国人写的 服务器也在国外 但是tunnel部属在国内 支持ngrok绝大多数功能 http www tunnel mobi 命令行中使用方法 在CMD命令中先切换到ngrok所在的位置再进行如下操
  • iOS给应用添加支持的文件类型/根据文件类型打开应用

    iOS给应用添加支持的文件类型 根据文件类型打开应用 之前写过类似的文章 IOS UTI 统一类型标识符 根据文件后缀打开APP 和 自定义UTI 注册你的APP所支持的文件类型 这里 再次总结说明 已经存在的UTL类型 苹果官方文档提供了
  • 编程之美 -- 中国象棋将帅问题

    下过中国象棋的朋友都知道 xff0c 双方的 将 和 帅 相隔遥远 xff0c 并且它们不能照面 在象棋残局中 xff0c 许多高手能利用这一规则走出精妙的杀招 假设棋盘上只有 将 和 帅 二子 xff08 为了下面叙述方便 xff0c 我
  • C++单元测试工具 -- CppUnit

    CppUnit 作为C 43 43 语言的一款测试工具 xff0c 其实也是一个开源项目 xff0c 与JUnit一样 xff0c 用来方便开发人员进行单元测试的工具 项目地址 xff1a http sourceforge net apps
  • 拒绝游戏!发愤图强!

    立帖为证 xff01 xff01 xff01
  • C++ STL — 第6章 STL容器(二)deque

    C 43 43 STL容器deque和vector很类似 xff0c 也是采用动态数组来管理元素 使用deque之前需包含头文件 xff1a include lt deque gt 它是定义在命名空间std内的一个class templat
  • C++ STL — 第6章 STL容器(三)list

    一 list基础 List使用一个双向链表来管理元素 图一显示了list的结构 图一 list的结构 任何型别只要具备赋值和可拷贝两种性质 xff0c 就可以作为list的元素 二 list的功能 list的内部结构和vector和dequ
  • STL list remove和sort函数

    include lt iostream gt include lt list gt include lt iterator gt using namespace std bool cmp int a int b return a gt b
  • 排序 -- 简单选择排序

    选择排序 思想 xff1a 每一趟 n i 43 1 xff08 i 61 1 2 3 n 1 xff09 个记录中选择关键字最小的记录作为有序序列的第i个记录 简单选择排序 xff1a 通过n i次关键字间的比较 xff0c 从n i 4
  • HDOJ 1106 排序

    题目地址 xff1a http acm hdu edu cn showproblem php pid 61 1106 Problem xff1a 输入一行数字 xff0c 如果我们把这行数字中的 5 都看成空格 xff0c 那么就得到一行用
  • ftp创建文件权限问题

    一 问题 有一个这样的需求 xff0c admin为一个Linux为其FTP应用创建的一个有权限限制的用户 xff0c 通过admin用户可以进行登录FTP服务 xff0c 登录FTP服务后 xff0c 创建文件夹 xff0c 该文件夹的用
  • lottie加载动画,第一次有延迟问题

    lottie是airbnb推出的一个直接将AE工程转化为动画的工具 ae project gt data json gt LottieComposition gt Lottie动画 之前做一个比较复杂的动画 xff0c 花了两天时间都在画各
  • CentOS 7防火墙快速开放端口配置方法

    CentOS 7防火墙快速开放端口配置方法 这篇文章主要为大家详细介绍了CentOS 7防火墙开放端口的快速方法 xff0c 感兴趣的小伙伴们可以参考一下 一 CentOS 7快速开放端口 xff1a CentOS升级到7之后 xff0c
  • C语言unsigned char、char与int之间的转换

    C语言unsigned char char与int之间的转换 2016年10月23日 18 40 50 bladeandmaster88 阅读数 xff1a 11347更多 个人分类 xff1a c语言基础 先来看一道题 xff1a cha
  • Android 内存分析(java/native heap内存、虚拟内存、处理器内存 )

    1 jvm 堆内存 dalvik 堆内存 不同手机中app进程的 jvm 堆内存是不同的 xff0c 因厂商在出厂设备时会自定义设置其峰值 比如 在Android Studio 创建模拟器时 xff0c 会设置jvm heap 默认384m
  • RabbitMq(一) RabbitMq工作模型

    RabbitMq工作模型 Mq基础RbbitMq工作模型RabbitMq基本使用原生apiSpring集成Springboot集成 RabbitMq进阶知识订单延迟关闭队列满了 总结 Mq基础 message queue 消息队列 特点 x
  • SSM整合_实现增删改查_基础环境搭建

    写在前面 SSM整合 年轻人的第一个增删改查 基础环境搭建 SSM整合 年轻人的第一个增删改查 查找 SSM整合 年轻人的第一个增删改查 新增 SSM整合 年轻人的第一个增删改查 修改 SSM整合 年轻人的第一个增删改查 删除 GitHub