使用SSM整合实现增删改查

SSM整合准备工作;
1、创建web模块,引入依赖;
2、创建数据表;
3、创建web.xml;
4、创建SpringMVC配置文件。

5、创建Spring的配置文件,配置扫描组件、配置数据源、配置事务管理器、配置开启事务注解;
6、创建service层,包括service接口和实现类;
7、搭建MyBatis环境,创建MyBatis核心配置文件,创建mapper接口,创建映射文件;
8、Spring整合MyBatis,在Spring的配置文件中,配置SqlSessionFactoryBean。

Spring整合MyBatis
1、搭建MyBatis环境,创建核心配置文件,创建mapper,映射文件;
2、在Spring配置文件中,添加两个配置,配置SqlSessionFactoryBean,配置扫描mapper接口MapperScannerConfigurer。

配置SqlSessionFactoryBean,可以从Spring IOC容器获取SqlSessionFactory对象
配置扫描mapper接口,将指定路径下所有接口,通过SqlSession对象创建对应的代理实现类对象,并交给Spring IOC容器管理。
就可以在service层,直接对依赖的mapper接口类型的对象进行自动装配。

引入依赖

<properties>
        <!--spring版本-->
        <spring.version>5.3.1</spring.version>
    </properties>

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--事务管理依赖的jar-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--mybatis和spring的整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
        <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 日志 Thymeleaf依赖slf4j日志,slf4j日志的具体实现logback依赖的jar -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- ServletAPI -->
        <!--前端控制器DispatcherServlet间接实现了HttpServlet所依赖的jar-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--json依赖的jar-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
        <!--文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>

添加页面employee_add

<form th:action="@{/emp}" method="post">
    <table>
        <tr>
            <th colspan="2">添加员工信息</th>
        </tr>
        <tr>
            <td>员工姓名</td>
            <td><input type="text" name="empName"/></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" name="age"/></td>
        </tr>
        <tr>
            <td>性别</td>
            <td><input type="radio" name="sex" value="男"/>男
                <input type="radio" name="sex" value="女"/>女
            </td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="添加">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

查询页面employee_list

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>员工列表页面</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<h1>enployee.html</h1>
<div id="app">
<table>
    <tr>
        <th colspan="6">员工列表</th>
    </tr>
    <tr>
        <th>id</th>
        <th>姓名</th>
        <th>性别</th>
        <th>年龄</th>
        <th>邮箱</th>
        <th>操作<a th:href="@{/to/add}">(添加)</a> </th>
    </tr>
    <tr th:each="employee : ${employeeList}">
        <td th:text="${employee.empId}"></td>
        <td th:text="${employee.empName}"></td>
        <td th:text="${employee.sex}"></td>
        <td th:text="${employee.age}"></td>
        <td th:text="${employee.email}"></td>
        <td>
            <a @click="deleteEmployee()" th:href="@{'/emp/'+${employee.empId}}">删除</a>
            <a th:href="@{'/emp/'+${employee.empId}}">更新</a>
        </td>
    </tr>
</table>
<form method="post">
    <input type="hidden" name="_method" value="delete">
</form>
</div>
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
    var vue=new Vue({
        el:"#app",
        methods:{
            deleteEmployee(){
                //获取form表单
                var form = document.getElementsByTagName("form")[0];
                //将超链接的href的值赋值给表单的action属性
                form.action=event.target.href;
                //提交表单
                form.submit();
                //阻止超链接默认行为
                event.preventDefault();
            }
        }
    });
</script>
</body>
</html>

更新页面employee_update

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>更新员工信息</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<h1>employee_update.html</h1>
</body>
<form th:action="@{/emp}" method="post">
    <input type="hidden" name="_method" value="put">
    <!--要修改的员工id-->
    <input type="hidden" name="empId" th:value="${employee.empId}">
    <table>
        <tr>
            <th colspan="2">更新员工信息</th>
        </tr>
        <tr>
            <td>员工姓名</td>
            <td><input type="text" name="empName" th:value="${employee.empName}"/></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" name="age" th:value="${employee.age}"/></td>
        </tr>
        <tr>
            <td>性别</td>
            <td><input type="radio" name="sex" value="男" th:field="${employee.sex}"/>男
                <input type="radio" name="sex" value="女" th:field="${employee.sex}"/>女
            </td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email" th:value="${employee.email}"></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="更新">
            </td>
        </tr>
    </table>
</form>
</html>

在添加一个static包

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>index.xml</h1>
<a th:href="@{/emp}">查看所有员工信息</a>

</body>
</html>

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_4_0.xsd"
         version="4.0">
    <!--配置SpringMVC编码过滤器-->
    <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>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--配置处理请求方式的过滤器-->
    <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>
    <display-name>Archetype Created Web Application</display-name>
    <!--配置前端控制器 DispatcherServlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--在加载DispatcherServlet时,读取SpringMVC配置文件
        默认在webapp/WEB-INF下读取配置文件,
        指定SpringMVC配置文件位置
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--设置加载DispatcherServlet的时机:在服务器启动时-->
        <load-on-startup>1</load-on-startup>

    </servlet>
    <!--配置servlet的映射关系-->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!--设置请求的路径
        / 表示处理所有的请求路径,处理.jsp -> tomcat提供JSPServlet处理jsp资源
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--配置监听器
    在读取spring配置文件的默认路径和名称:/WEB-INF,
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--设置上下文参数自定义spring配置文件的路径和名称-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <context-param>
        <param-name/>
        <param-value/>
    </context-param>
</web-app>
映射文件EmloyeeMapper.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">
<!--MyBatis的映射文件 编写sql-->
<!--一个数据表对应一个实体类,一个实体类对应一个mapper映射文件-->
<mapper namespace="com.dzqc.ssm.mapper.EmployeeMapper">

        <!--List<Employee> getAllEmployees();-->
    <select id="getAllEmployees" resultType="Employee">
        select * from t_emp
    </select>
    <!--Integer insertEmployee(Employee employee);-->
    <insert id="insertEmployee">
            insert into t_emp values (null,#{empName},#{age},#{sex},#{email})
    </insert>
    <!--Integer updateEmployee(Employee employee);-->
    <update id="updateEmployee">
        update t_emp set emp_name=#{empName},age=#{age},sex=#{sex},email=#{email} where emp_id=#{empId}
    </update>
    <!--Employee queryEmployee(@Param("empId") Integer id);-->
    <select id="queryEmployee" resultType="Employee">
        select*from t_emp where emp_id=#{empId}
    </select>
    <!--Integer deleteEmployee(@Param("empId") Integer id);-->
    <delete id="deleteEmployee">
        delete from t_emp where emp_id=#{empId}
    </delete>
</mapper>

扫描二维码关注公众号,回复: 16506310 查看本文章

 jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm212?serverTimezone=UTC&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

mybatis-config

<?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>
    <!--读取配置文件-->
    <properties resource="jdbc.properties"></properties>
    <!--全局设置-->
    <settings>
        <!--开启驼峰命名自动映射  即下划线自动映射成驼峰命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--引入映射文件-->
    <mappers>
        <!--<mapper resource="com\dzqc\mapper\EmpMapper.xml"/>-->
        <package name="com.dzqc.ssm.mapper"/>
    </mappers>
</configuration>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--扫描组件(除)-->
    <context:component-scan base-package="com.dzqc.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--引入属性文件,可以使用${}获取key对应的值-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--配置数据源-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>


    <!--配置开启事务管理,可以对注解 标识的方法或类中所有方法进行事务管理-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    <!--配置SqlSessionFactoryBean,可以获取SpringIOC容器中的SessionFactory对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--设置MyBatis核心配置文件的位置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!--配置数据源-->
        <property name="dataSource" ref="druidDataSource"></property>
        <!--设置类型别名-->
        <property name="typeAliasesPackage" value="com.dzqc.ssm.pojo"></property>
        <!--设置映射文件位置,当映射文件和接口不在同一-->
       <!-- <property name="mapperLocations" value="classpath:mapper/*.xml"></property>-->

    </bean>
    <!--配置扫描mapper接口,可以将指定包下所有接口,
    通过SqlSession对象创建mapper接口的代理实现类对象,并将对象交给IOC容器处理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dzqc.ssm.mapper"></property>
    </bean>
</beans>

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:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--扫描组件(除)-->
    <context:component-scan base-package="com.dzqc.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--引入属性文件,可以使用${}获取key对应的值-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--配置数据源-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>


    <!--配置开启事务管理,可以对注解 标识的方法或类中所有方法进行事务管理-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    <!--配置SqlSessionFactoryBean,可以获取SpringIOC容器中的SessionFactory对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--设置MyBatis核心配置文件的位置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!--配置数据源-->
        <property name="dataSource" ref="druidDataSource"></property>
        <!--设置类型别名-->
        <property name="typeAliasesPackage" value="com.dzqc.ssm.pojo"></property>
        <!--设置映射文件位置,当映射文件和接口不在同一-->
       <!-- <property name="mapperLocations" value="classpath:mapper/*.xml"></property>-->

    </bean>
    <!--配置扫描mapper接口,可以将指定包下所有接口,
    通过SqlSession对象创建mapper接口的代理实现类对象,并将对象交给IOC容器处理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.dzqc.ssm.mapper"></property>
    </bean>
</beans>

控制层EmployeeController

数据访问层EmployeeMapper


 实体类Employee

 业务逻辑层

项目结构

查询页面

更新页面

删除页面

添加页面 

数据库 

/*
Navicat MySQL Data Transfer

Source Server         : db
Source Server Version : 50735
Source Host           : localhost:3306
Source Database       : ssm

Target Server Type    : MYSQL
Target Server Version : 50735
File Encoding         : 65001

Date: 2022-12-13 11:20:11
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_emp
-- ----------------------------
DROP TABLE IF EXISTS `t_emp`;
CREATE TABLE `t_emp` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` char(1) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_emp
-- ----------------------------

猜你喜欢

转载自blog.csdn.net/m0_68367226/article/details/130231966