SSM 框架整合案例

article/2025/9/18 18:04:05

项目简介

使用 SSM 框架搭建出一套简单的 CRUD 项目示例,主要涉及两张表:员工表和部门表,其中每个员工都对应一个部门。

主要实现的功能

1、分页查询所有员工信息并展示列表。

2、添加一条员工的信息。

3、新增数据需要校验:

  • jQuery 前端校验用户名和邮箱是否合法。
  • Ajax 请求校验用户名是否重复。
  • JSR 303 后端校验用户名、邮箱是否合法以及用户名是否重复。

4、编辑修改某条员工的信息。

5、删除某条员工的信息,批量删除所选员工的信息。

6、RESTful 风格的URI。

涉及的技术

1、后端框架:SSM(Spring 5 + Spring MVC + MyBatis 3)+ Maven 3.6.3

2、MyBatis 分页插件:PageHelper

3、MyBatis 逆向工程:MyBatis Generator

4、数据库:MySQL 5.7 + Druid 数据库连接池

5、前端框架:BootStrap 5

最终效果:

一、搭建环境

1、搭建框架、引入依赖和Tomcat

(1)创建一个 Maven 工程:

 创建效果:

(2)导入依赖:

登陆Maven的中央仓库从仓库中找到自己需要的依赖(可以直接复制我的依赖):

Maven中央仓库https://mvnrepository.com/

 在pom.xml中导入所需要的依赖

 

下面代码中 connnecter和数据库连接池进行了修改,与视频中不同

<?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.atguigu</groupId><artifactId>ssm-crud-hjr</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><!--引入项目依赖的jar包--><dependencies><!-- MBG --><!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.5</version></dependency><!-- SpringMVC、Spring --><!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.7.RELEASE</version></dependency><!-- Spring-Jdbc --><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.3.7.RELEASE</version></dependency><!-- Spring面向切面编程 --><!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.3.7.RELEASE</version></dependency><!--MyBatis --><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.2</version></dependency><!-- MyBatis整合Spring的适配包 --><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency><!--MySQL驱动与Druid数据库连接池--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.25</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.7</version></dependency><!-- (jstl,servlet-api,junit) --><!-- https://mvnrepository.com/artifact/jstl/jstl --><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.0.1</version><scope>provided</scope></dependency><!-- junit --><!-- https://mvnrepository.com/artifact/junit/junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies></project>

 记得点击import,导入的依赖才会生效!

(3)创建web.xml

 (4)配置Tomcat(默认读者已经会按照了Tomcat,康师傅JavaWeb课程中教过的)

 

 

 提交Apply即可


(5)引入bootstrap前端框架

 进入bootstrap中文文档bootstrap V3 中文文档https://v3.bootcss.com/

 由于官网已经找不到视频教程中的3.3.7版本,我在这里提供一下

链接:https://pan.baidu.com/s/1GGOSc_NfG7yO-VO8GOFM2A
提取码:ytq6

webapp文件夹下创建static文件夹后,把bootstrap复制进去

根据bootstrap官网的介绍,如果想要使用bootstrap,只需要将引入相应的css文件和js文件

根据基本模板,将引入的代码复制(图片仅提供操作参考)

(视频教程所用的3.1.7版本直接复制我代码)

(6)创建index.jsp

在webapp下创建index.jsp

<%--Created by IntelliJ IDEA.User: 1Date: 2022/3/16Time: 20:46To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><%--引入jquery--%><script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script><%--引入样式--%><link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"><script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body><button>按钮</button>
</body>
</html>

点击debug当前的tomcat工程, 尝试下button的功能

 

成功:

 

 也可以根据bootstrap中文文档中的全局css样式中的按钮样式来美化button

加入到index.jsp中

重新运行tomcat

 


(7)配置web.xml

 web.xml中

此时,先去resouces下创建spring 的配置文件 applicationContext.xml(暂时不配置

在WEB-INF下创建springMVC配置文件

 web.xml中配置springmvc的前端控制器,用于拦截所有请求

 加入字符编码过滤器(设置为UTF-8)(一定要放在所有的过滤器之前)

因为Java中的字符编码,默认为:ISO-8859-1(西方编码)。这种编码方式为单字节码,只支持英文、俄文、葡萄牙文等乱七八糟文,不支持中文。因此,我们需要对JSP页面或者Servlet中进行字符编码集的处理,国际编码(UTF-8)。

 使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求

       因为我们在开发中已经规范了一种风格就是MVC的REST风格,它拥有四种请求,分别是:GET、POST、PUT、DELETE。

      分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE用来删除资源。REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。通常的浏览器却只支持get和post请求,这个时候就需要用到我们的HiddenHttpMethodFilter 过滤器来将post请求转换为put跟delete请求。

 web.xml 的基本配置如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"><!--1、启动Spring的容器  --><!-- needed for ContextLoaderListener --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!-- Bootstraps the root web application context before servlet initialization --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--2、springmvc的前端控制器,拦截所有请求  --><!-- The front controller of this Spring Web application, responsible for handling all application requests --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><!-- Map all requests to the DispatcherServlet for handling --><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 3、字符编码过滤器,一定要放在所有过滤器之前 --><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><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><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 4、使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 --><filter><filter-name>HiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class></filter><filter-mapping><filter-name>HiddenHttpMethodFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><filter><filter-name>HttpPutFormContentFilter</filter-name><filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class></filter><filter-mapping><filter-name>HttpPutFormContentFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>

src/main/java下创建相应的package

WEB-INF下创建lib、views包

配置SpringMVC

打开webapp下的dispatcherServlet-servlet.xml,其主要包含网站跳转逻辑的控制,配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"><!--SpringMVC的配置文件,包含网站跳转逻辑的控制,配置  --><context:component-scan base-package="com.atguigu" use-default-filters="false"><!--只扫描控制器。  --><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><property name="suffix" value=".jsp"></property></bean><!--两个标准配置  --><!-- 将springmvc不能处理的请求交给tomcat --><mvc:default-servlet-handler/><!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 --><mvc:annotation-driven/></beans>

 配置Spring(resources/applicationContext.xml)

 创建图中的绿色标记  (resources/dbconfig.properties)

SQLyog中创建相应的数据库和表

 (resources/applicationContext.xml)

 配置和MyBatis的整合,创建相应的xml文件和mapper文件夹

applicationContext.xml的目前配置

核心点:<!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) -->

<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"><context:component-scan base-package="com.atguigu"><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller" /></context:component-scan><!-- Spring的配置文件,这里主要配置和业务逻辑有关的 --><!--=================== 数据源,事务控制,xxx ================--><context:property-placeholder location="classpath:dbconfig.properties" /><bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property></bean><!--================== 配置和MyBatis的整合=============== --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 指定mybatis全局配置文件的位置 --><property name="configLocation" value="classpath:mybatis-config.xml"></property><property name="dataSource" ref="pooledDataSource"></property><!-- 指定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.atguigu.crud.dao"></property></bean><!-- 配置一个可以执行批量的sqlSession --><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg><constructor-arg name="executorType" value="BATCH"></constructor-arg></bean><!--=============================================  --><!-- ===============事务控制的配置 ================--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--控制住数据源  --><property name="dataSource" ref="pooledDataSource"></property></bean><!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式)  --><aop:config><!-- 切入点表达式 --><aop:pointcut expression="execution(* com.atguigu.crud.service..*(..))" id="txPoint"/><!-- 配置事务增强 --><aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/></aop:config><!--配置事务增强,事务如何切入  --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 所有方法都是事务方法 --><tx:method name="*"/><!--以get开始的所有方法  --><tx:method name="get*" read-only="true"/></tx:attributes></tx:advice><!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) --></beans>


Mybatis逆向工程

pom.xml中添加相应依赖(添加后,记得点右下角的import

        <!-- MBG --><!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.5</version></dependency>

在ssm-curd下创建mbg.xml

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><!--targetRuntime设置生成的模式--><context id="DB2Tables" targetRuntime="MyBatis3"><!--阻止注释的生成--><commentGenerator><property name="suppressAllComments" value="true"/></commentGenerator><!--配置数据库连接信息--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/ssm_crud"userId="root"password="abc123"/><javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver><!--指定 Java Bean 生成的位置--><javaModelGeneratortargetPackage="com.atguigu.crud.bean"targetProject=".\src\main\java"><property name="enableSubPackages" value="true"/><property name="trimStrings" value="true"/></javaModelGenerator><!--指定 SQL 映射文件生成的位置--><sqlMapGeneratortargetPackage="mapper"targetProject=".\src\main\resources"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!--指定 mapper(dao) 接口生成的位置--><javaClientGenerator type="XMLMAPPER"targetPackage="com.atguigu.crud.dao"targetProject=".\src\main\java"><property name="enableSubPackages" value="true"/></javaClientGenerator><!--table 指定每个表的生成策略--><table tableName="tbl_emp" domainObjectName="Employee"/><table tableName="tbl_dept" domainObjectName="Department"/></context>
</generatorConfiguration>

 在src/main/java/com.atguigu.crud/test下创建MBGTest.class

MBGTest.class

package com.atguigu.crud.test;import java.io.File;
import java.util.ArrayList;
import java.util.List;import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;public class MBGTest {public static void main(String[] args) throws Exception {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);}
}

 运行MGBTest

 生成成功!

修改Mapper文件

 bean/Empployee新增内容

 private Department department;public Department getDepartment() {return department;}public void setDepartment(Department department) {this.department = department;}

 dao/EmployeeMapper新增内容

    /*新增的方法*/List<Employee> selectByExampleWithDept(EmployeeExample example);/*新增的方法*/Employee selectByPrimaryKeyWithDept(Integer empId);

 resources/mapper/EmployeeMapper.xml 新增内容(视频中加的很乱,大家直接看代码吧)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.crud.dao.EmployeeMapper"><resultMap id="BaseResultMap" type="com.atguigu.crud.bean.Employee"><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" /></resultMap><resultMap type="com.atguigu.crud.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.atguigu.crud.bean.Department"><id column="dept_id" property="deptId"/><result column="dept_name" property="deptName"/></association></resultMap><sql id="Example_Where_Clause"><where><foreach collection="oredCriteria" item="criteria" separator="or"><if test="criteria.valid"><trim prefix="(" prefixOverrides="and" suffix=")"><foreach collection="criteria.criteria" item="criterion"><choose><when test="criterion.noValue">and ${criterion.condition}</when><when test="criterion.singleValue">and ${criterion.condition} #{criterion.value}</when><when test="criterion.betweenValue">and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}</when><when test="criterion.listValue">and ${criterion.condition}<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach></when></choose></foreach></trim></if></foreach></where></sql><sql id="Update_By_Example_Where_Clause"><where><foreach collection="example.oredCriteria" item="criteria" separator="or"><if test="criteria.valid"><trim prefix="(" prefixOverrides="and" suffix=")"><foreach collection="criteria.criteria" item="criterion"><choose><when test="criterion.noValue">and ${criterion.condition}</when><when test="criterion.singleValue">and ${criterion.condition} #{criterion.value}</when><when test="criterion.betweenValue">and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}</when><when test="criterion.listValue">and ${criterion.condition}<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">#{listItem}</foreach></when></choose></foreach></trim></if></foreach></where></sql><sql id="Base_Column_List">emp_id, emp_name, gender, email, d_id</sql><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><!--   List<Employee> selectByExampleWithDept(EmployeeExample example);Employee selectByPrimaryKeyWithDept(Integer empId); --><!-- 查询员工同时带部门信息 --><select id="selectByExampleWithDept" resultMap="WithDeptResultMap">select<if test="distinct">distinct</if><include refid="WithDept_Column_List" />FROM tbl_emp eleft 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></select><select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">select<include refid="WithDept_Column_List" />FROM tbl_emp eleft join tbl_dept d on e.`d_id`=d.`dept_id`where emp_id = #{empId,jdbcType=INTEGER}</select><!-- 查询员工不带部门信息的 --><select id="selectByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultMap="BaseResultMap">select<if test="distinct">distinct</if><include refid="Base_Column_List" />from tbl_emp<if test="_parameter != null"><include refid="Example_Where_Clause" /></if><if test="orderByClause != null">order by ${orderByClause}</if></select><select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">select<include refid="Base_Column_List" />from tbl_empwhere emp_id = #{empId,jdbcType=INTEGER}</select><delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">delete from tbl_empwhere emp_id = #{empId,jdbcType=INTEGER}</delete><delete id="deleteByExample" parameterType="com.atguigu.crud.bean.EmployeeExample">delete from tbl_emp<if test="_parameter != null"><include refid="Example_Where_Clause" /></if></delete><insert id="insert" parameterType="com.atguigu.crud.bean.Employee">insert into tbl_emp (emp_id, emp_name, gender, email, d_id)values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER})</insert><insert id="insertSelective" parameterType="com.atguigu.crud.bean.Employee">insert into tbl_emp<trim prefix="(" suffix=")" suffixOverrides=","><if test="empId != null">emp_id,</if><if test="empName != null">emp_name,</if><if test="gender != null">gender,</if><if test="email != null">email,</if><if test="dId != null">d_id,</if></trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="empId != null">#{empId,jdbcType=INTEGER},</if><if test="empName != null">#{empName,jdbcType=VARCHAR},</if><if test="gender != null">#{gender,jdbcType=CHAR},</if><if test="email != null">#{email,jdbcType=VARCHAR},</if><if test="dId != null">#{dId,jdbcType=INTEGER},</if></trim></insert><select id="countByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultType="java.lang.Long">select count(*) from tbl_emp<if test="_parameter != null"><include refid="Example_Where_Clause" /></if></select><update id="updateByExampleSelective" parameterType="map">update tbl_emp<set><if test="record.empId != null">emp_id = #{record.empId,jdbcType=INTEGER},</if><if test="record.empName != null">emp_name = #{record.empName,jdbcType=VARCHAR},</if><if test="record.gender != null">gender = #{record.gender,jdbcType=CHAR},</if><if test="record.email != null">email = #{record.email,jdbcType=VARCHAR},</if><if test="record.dId != null">d_id = #{record.dId,jdbcType=INTEGER},</if></set><if test="_parameter != null"><include refid="Update_By_Example_Where_Clause" /></if></update><update id="updateByExample" parameterType="map">update tbl_empset emp_id = #{record.empId,jdbcType=INTEGER},emp_name = #{record.empName,jdbcType=VARCHAR},gender = #{record.gender,jdbcType=CHAR},email = #{record.email,jdbcType=VARCHAR},d_id = #{record.dId,jdbcType=INTEGER}<if test="_parameter != null"><include refid="Update_By_Example_Where_Clause" /></if></update><update id="updateByPrimaryKeySelective" parameterType="com.atguigu.crud.bean.Employee">update tbl_emp<set><if test="empName != null">emp_name = #{empName,jdbcType=VARCHAR},</if><if test="gender != null">gender = #{gender,jdbcType=CHAR},</if><if test="email != null">email = #{email,jdbcType=VARCHAR},</if><if test="dId != null">d_id = #{dId,jdbcType=INTEGER},</if></set>where emp_id = #{empId,jdbcType=INTEGER}</update><update id="updateByPrimaryKey" parameterType="com.atguigu.crud.bean.Employee">update tbl_empset emp_name = #{empName,jdbcType=VARCHAR},gender = #{gender,jdbcType=CHAR},email = #{email,jdbcType=VARCHAR},d_id = #{dId,jdbcType=INTEGER}where emp_id = #{empId,jdbcType=INTEGER}</update>
</mapper>

  pom.xml中加入spring单位测试模块

        <!--Spring-test --><!-- https://mvnrepository.com/artifact/org.springframework/spring-test --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.3.7.RELEASE</version></dependency>

进行mapper的功能测试,新建test下MapperTest.class

MapperTest

package com.atguigu.crud.test;import java.util.UUID;import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.atguigu.crud.dao.DepartmentMapper;
/*** 测试dao层的工作* @author lfy*推荐Spring的项目就可以使用Spring的单元测试,可以自动注入我们需要的组件*1、导入SpringTest模块*2、@ContextConfiguration指定Spring配置文件的位置*3、直接autowired要使用的组件即可*/@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {@AutowiredDepartmentMapper departmentMapper;/*** 测试DepartmentMapper*/@Testpublic void testCRUD() {/*	//1、创建SpringIOC容器ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");//2、从容器中获取mapperDepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/System.out.println(departmentMapper);}
}


http://chatgpt.dhexx.cn/article/D6CFJCLu.shtml

相关文章

JavaEE_SSM框架_SSM项目案例

SSM项目之【千里之行&#xff0c;始于足下】 创建由【SSM】框架搭建的JavaWeb项目的步骤如下&#xff1a; Ⅰ、创建动态Web项目 Ⅱ、拷贝SSM项目所需的jar包 将前期【SSM项目】所需的【32】个jar包拷贝到【WebContent】——【WEB-INF】——【lib】目录下 …

SSM框架整合完整案例

SSM框架整合 一、整合思路二、案例实战1. 项目前期准备2. 整合dao层① mybatis全局配置文件(SqlConfig.xml)② 配置spring.xml③ 编写POJO类(java bean)④ 编写ItemsMapper.xml⑤ 编写ItemsMapper.java接口⑥ 测试dao层 3. 整合service层(使用注解)4. 整合spring mvc① 编写Con…

简单易懂:SSM入门级项目整合实例教程+附项目源码

欢迎关注点赞评论&#xff0c;共同学习&#xff0c;共同进步&#xff01; 你的点赞、关注、评论、是我创作的动力&#xff01; -------希望我的文章对你有所帮助-------- 目录 一、前言 二、推荐开发及运行环境 三、项目基本结构 四、创建一个普通JAVAEE-WEB项目 五、搭建…

Maven+SSM框架项目实例

一、项目环境 开发系统&#xff1a;Window10开发工具&#xff1a;IDEAJDK&#xff1a;1.8框架&#xff1a;MavenSpringSpringMVCMybatis数据库&#xff1a;Mysql 二、项目结构 项目文件架构&#xff1a; 三、Maven配置 pom.xml&#xff1a; <properties><!-- s…

SSM框架整合详细案例

目录描述 一、创建web项目(使用idea maven)二、使用maven添加依赖1、在pom.xml中添加项目所需的所有依赖2、添加tomcat运行驱动 三、建立整体项目架构四、搭建mybatis1、编写mybatis-config.xml2、编写数据库连接配置文件3、编写spring-mybatis.xml4、编写pojo和dao层5、编写映…

SSM框架详细实例讲解

SSM框架简介 SSM框架&#xff0c;是Spring Spring MVC MyBatis的缩写&#xff0c;这个是继SSH之后&#xff0c;目前比较主流的Java EE企业级框架&#xff0c;适用于搭建各种大型的企业级应用系统。 我们先大概的回顾一下吧。1.Spring简介 Spring是一个开源框架&…

SSM框架搭建实例

SSM框架搭建简单实例 - 搭建步骤 需求分析&#xff1a; 实现用户表信息的增删改查 1. 开发环境 环境 &#xff1a; JDK 1.8 软件 &#xff1a; myeclipse 数据库 &#xff1a; MySql 2. 创建数据库 数据库名称&#xff1a;ssm 字符集&#xff1a;…

java ssm框架项目_3个SSM框架应用实例教程

SSM框架简介 SSM(SpringSpringMVCMyBatis)框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成&#xff0c;常作为数据源较简单的web项目的框架。 文章主要介绍3个SSM框架应用的实例教程&#xff0c;非常适合想学习应用该整合框架的小伙伴。 该项目假设为开发一个简单的用…

SSM框架整合实例

1.数据准备 创建一个数据库并取名为ssm&#xff0c;在数据库ssm下创建user表&#xff1b;对应的sql脚本如下&#xff0c;这里我们直接使用navicat工具更方便。 create database ssm;use ssm; create table user(id int primary key auto_increment,username varchar(20),pass…

SSM框架整合+简单案例实现

SSM框架整合简单案例实现 文章目录 前言一、SpringSpringMVCMybatis框架整合1.建立一个新的web项目2.所需jar包3.建立数据库表与实体类之间的映射4.web.xml5.数据库信息db.properties6.Spring与Mybatis的整合7.SpringMVC基本配置 二、整合测试1.结构展示2.studentMapper.xml3.s…

ssm框架的简单案例

学完ssm框架后做了一个简单的案例&#xff0c;实现简单的增删改查。 项目结构图&#xff1a; 看项目结构&#xff1a; 关键代码&#xff1a; 前端是jsp技术&#xff0c;当然也可以用vue分离的自己选择就好。 订单页面&#xff1a; <% page language"java&quo…

SSM框架开发-基础案例

SSM框架整合基础案例详解 1.数据库环境 创建一个存放书籍数据的数据库表 CREATE DATABASE ssmbuild;USE ssmbuild;DROP TABLE IF EXISTS books;CREATE TABLE books (bookID INT(10) NOT NULL AUTO_INCREMENT COMMENT 书id,bookName VARCHAR(100) NOT NULL COMMENT 书名,bookCou…

SSM框架简单实例

1、SSM框架 SSM&#xff08;SpringSpringMVCMyBatis&#xff09;框架集由Spring、SpringMVC、MyBatis三个开源框架整合而成&#xff0c;常作为数据源较简单的web项目的框架。 2、简单实例 &#xff08;1&#xff09;项目结构 &#xff08;2&#xff09;PageBean.java packa…

用SSM实现简单实例

SSM的简例实现 这是项目完整代码的链接地址 [https://download.csdn.net/download/m0_46308149/12961224]源码地址 SSM介绍 SSM&#xff08;SpringSpringMVCMyBatis&#xff09;框架集由Spring、MyBatis两个开源框架整合而成&#xff08;SpringMVC是Spring中的部分内容&am…

SpringMVC笔记——SSM框架搭建简单实例

简介 SpringSpringMVCMyBatis框架&#xff08;SSM&#xff09;是比较热门的中小型企业级项目开发的框架&#xff0c;对于新手来说也是比较容易学习入门的。虽说容易&#xff0c;但在框架搭建过程中仍然遇到了许多问题&#xff0c;因此用实例记录下来吧。 实例 第一步——导包 S…

SSM框架整合+案例

SSM框架整合 1、环境要求2、数据库环境3、基本环境搭建3.1 创建项目3.2 Maven项目添加web支持3.3 配置pom.xml文件3.4 建立框架的基本结构和配置文件3.4.1 创建包3.4.2 添加配置文件3.4.3 database.properties文件3.4.4 mybatis-config.xml 文件3.4.5 applicationContext.xml 文…

C# SqlHelper类的使用

SqlHelper类 1.首先SqlHelper类是一个基于.NET Framework的数据库操作组件&#xff0c;包含了数据库的操作方法。可以简化在C#中使用ADO.NET连接数据库时每次都要编写连接、打开、执行SQL语句的代码&#xff0c;它将每次连接都要写的代码封装成方法&#xff0c;把要执行的SQL语…

SqlHelper类(C#)

大神可以绕道了... 目的&#xff1a;搜集SqlHelper类 自己写的一个SQLHelper类&#xff0c;如下&#xff1a; 编辑App.config节点&#xff0c;添加<connectionStrings>节点&#xff0c;并根据实际填上相应的参数 <?xml version"1.0" encoding"utf…

SQLHelper

前言 小编在最近的学习过程中用到了SQLHelper&#xff0c;说起来&#xff0c;小编也是有点懒&#xff0c;虽然是用到了&#xff0c;但是也没有用明白&#xff0c;开始的时候也没有好好的研究&#xff0c;直到后来报错了&#xff0c;才下定决心好好好学习了解一下这个东西。下面…

sqlhelper 的使用 (C#)超级详细的入门教程

sql helper 的使用 &#xff08;C#&#xff09;小白教程 提到CRUD&#xff0c;很多刚入门的小白总是来一条写一条连接&#xff0c;先建立连接connection 打开连接 open 来查询query 最后别忘了关闭连接 close 。 要是一次写多个操作&#xff0c;那一遍一遍写下来肯定麻木了。…