SSM框架实现增删改查

SSM框架实现增删改查

pom.xml


<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>employeeartifactId>
    <version>1.0-SNAPSHOTversion>

    <packaging>warpackaging>

    <properties>
        <maven.compiler.source>8maven.compiler.source>
        <maven.compiler.target>8maven.compiler.target>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>5.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.6version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.9version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.30version>
        dependency>
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelperartifactId>
            <version>5.2.0version>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.12.1version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
            <version>3.0.12.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>RELEASEversion>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>RELEASEversion>
            <scope>compilescope>
        dependency>
    dependencies>



project>

src/main/resources/jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/employee?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.username=
jdbc.password=

src/main/resources/log4j.xml

 DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
        layout>
    appender>
    <logger name="java.sql">
        <level value="debug"/>
    logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    root>
log4j:configuration>

src/main/resources/mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <settings>
        
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>


    
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">plugin>
    plugins>

configuration>

src/main/resources/spring.xml


<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.moon.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    
    <context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}">property>
        <property name="url" value="${jdbc.url}">property>
        <property name="password" value="${jdbc.password}">property>
        <property name="username" value="${jdbc.username}">property>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        
        <property name="dataSource" ref="dataSource">property>
        
        <property name="typeAliasesPackage" value="com.moon.ssm.pojo">property>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.moon.ssm.mapper">property>
    bean>
beans>

src/main/resources/springmvc.xml


<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">
    
    
    <context:component-scan base-package="com.moon.ssm.controller">context:component-scan>
    
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    bean>
                property>
            bean>
        property>
    bean>

    
    <mvc:default-servlet-handler/>

    
    <mvc:annotation-driven/>

    
    <mvc:view-controller path="/" view-name="index">mvc:view-controller>
    <mvc:view-controller path="/to/add" view-name="employee_add">mvc:view-controller>
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    bean>
beans>

src/main/webapp/WEB-INF/web.xml


<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">

    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>HiddenHttpMethodFilterfilter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring.xmlparam-value>
    context-param>
web-app>

com/moon/ssm/pojo/Employee.java

package com.moon.ssm.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @Author moon
 * @Date 2023/4/15 0:51
 * @Description
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Employee {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;
    private String email;
}

com/moon/ssm/controller/EmployeeController.java

package com.moon.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.moon.ssm.pojo.Employee;
import com.moon.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/employee/page/{pageNum}", method = RequestMethod.GET)
    public String getEmployeePage(@PathVariable("pageNum") Integer pageNum, Model model) {
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);
        model.addAttribute("aaa",1);
        model.addAttribute("page", page);
        return "employee_list";
    }

    @RequestMapping(value = "/employee/page", method = RequestMethod.POST)
    public String addEmployee(Employee employee) {
        employeeService.addEmployee(employee);
        return "redirect:/employee/page/1";
    }

    @RequestMapping(value = "/employee/{pageNum}/{id}", method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("pageNum") Integer pageNum, @PathVariable("id") Integer id) {
        employeeService.deleteEmployee(id);
        return "redirect:/employee/page/{pageNum}";
    }

    @RequestMapping(value = "/employee/{pageNum}/{id}", method = RequestMethod.GET)
    public String getUpdate(@PathVariable("id") Integer id, @PathVariable("pageNum") Integer pageNum, Model model) {
        System.out.println("-------" + id);
        Employee employee = employeeService.getEmployeeById(id);
        model.addAttribute("employee", employee);
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);
        model.addAttribute("page", page);
        return "employee_update";
    }

    @RequestMapping(value = "/employee/{pageNum}", method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeService.updateEmployee(employee);
        return "redirect:/employee/page/{pageNum}";
    }
}

com/moon/ssm/service/EmployeeService.java

package com.moon.ssm.service;

import com.github.pagehelper.PageInfo;
import com.moon.ssm.pojo.Employee;

import java.util.List;

public interface EmployeeService {

    List<Employee> getAllEmployee();

    PageInfo<Employee> getEmployeePage(Integer pageNum);

    void addEmployee(Employee employee);

    void deleteEmployee(Integer id);

    Employee getEmployeeById(Integer id);

    void updateEmployee(Employee employee);
}

com/moon/ssm/service/impl/EmployeeServiceImpl.java

package com.moon.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moon.ssm.mapper.EmployeeMapper;
import com.moon.ssm.pojo.Employee;
import com.moon.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> getAllEmployee() {
        return employeeMapper.getAllEmployee();
    }

    @Override
    public PageInfo<Employee> getEmployeePage(Integer pageNum) {
        PageHelper.startPage(pageNum, 4);
        List<Employee> list = employeeMapper.getAllEmployee();
        PageInfo<Employee> page = new PageInfo<>(list, 5);
        return page;
    }

    public void addEmployee(Employee employee) {
        employeeMapper.addEmployee(employee);
    }

    @Override
    public void deleteEmployee(Integer id) {
        employeeMapper.deleteEmployee(id);
    }

    @Override
    public Employee getEmployeeById(Integer id) {
        Employee employee = employeeMapper.getEmployeeById(id);
        return employee;
    }

    @Override
    public void updateEmployee(Employee employee) {
        employeeMapper.updateEmployee(employee);
    }


}

com/moon/ssm/mapper/EmployeeMapper.java

package com.moon.ssm.mapper;

import com.moon.ssm.pojo.Employee;

import java.util.List;

/**
 * @Author moon
 * @Date 2023/4/15 0:54
 * @Description
 */
public interface EmployeeMapper {

    List<Employee> getAllEmployee();

    void addEmployee(Employee employee);

    void deleteEmployee(Integer id);

    Employee getEmployeeById(Integer id);

    void updateEmployee(Employee employee);
}

com/moon/ssm/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.moon.ssm.mapper.EmployeeMapper">
    <!--List<Employee> getAllEmployee()-->
    <select id="getAllEmployee" resultType="employee">
        select * from t_emp
    </select>

    <!--void addEmployee(Employee employee)-->
    <insert id="addEmployee" useGeneratedKeys="true" keyProperty="empId">
        insert into t_emp values (null , #{empName}, #{age}, #{gender}, #{email})
    </insert>
    
    <!--void deleteEmployee(Integer id);-->
    <delete id="deleteEmployee">
        delete from t_emp where emp_id = #{id}
    </delete>

    <!--Employee getEmployeeById(Integer id);-->
    <select id="getEmployeeById" resultType="employee">
        select * from t_emp where emp_id = #{id};
    </select>

    <!--void updateEmployee(Employee employee);-->
    <update id="updateEmployee">
        update t_emp set emp_name=#{empName},age=#{age},gender=#{gender},email=#{email} where emp_id=#{empId}
    </update>
</mapper>

src/main/webapp/WEB-INF/templates/index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

src/main/webapp/WEB-INF/templates/employee_list.html

<!DOCTYPE html>
<!--suppress ALL-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>employee info</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
    <div id="app">
        <table>
            <tr>
                <th colspan="6">Employee Info</th>
            </tr>
            <tr>
                <th>emp_id</th>
                <th>emp_name</th>
                <th>age</th>
                <th>gender</th>
                <th>email</th>
                <th>options(<a th:href="@{'/to/add'}">add</a>)</th>
            </tr>
            <tr th:each="employee,status : ${page.list}">
                <td th:text="${status.count}"></td>
                <td th:text="${employee.empName}"></td>
                <td th:text="${employee.age}"></td>
                <td th:text="${employee.gender}"></td>
                <td th:text="${employee.email}"></td>
                <td>
                    <a @click="deleteEmployee()" th:href="@{'/employee/'+${page.pageNum}+'/'+${employee.empId}}">delete</a>
                    <a th:href="@{'/employee/'+${page.pageNum}+'/'+${employee.empId}}">update</a>
                </td>
            </tr>
            <tr>
                <td colspan="6">
                    <span th:if="${page.hasPreviousPage}">
                        <a th:href="@{/employee/page/1}">首页</a>
                        <a th:href="@{'/employee/page/'+${page.prePage}}">上一页</a>
                    </span>
                    <span th:each="num : ${page.navigatepageNums}">
                        <a th:if="${page.pageNum==num}"
                           th:href="@{'/employee/page/'+${num}}"
                           th:text="' ['+${num}+'] '" style="color: red;">
                        </a>
                        <a th:if="${page.pageNum!=num}"
                           th:href="@{'/employee/page/'+${num}}"
                           th:text="${num}">
                        </a>
                    </span>
                    <span th:if="${page.hasNextPage}">
                        <a th:href="@{'/employee/page/'+${page.nextPage}}">下一页</a>
                        <a th:href="@{'/employee/page/'+${page.pages}}">末页</a>
                    </span>
                </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() {
                var form = document.getElementsByTagName("form")[0];
                form.action = event.target.href;
                form.submit();
                event.preventDefault();
            }
        }
    })
</script>
</body>
</html>

src/main/webapp/WEB-INF/templates/employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>add employee</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<form th:action="@{/employee/page}" method="post">
   <table>
        <tr>
            <th colspan="4">add employee</th>
        </tr>
        <tr>
            <td>empName</td>
            <td>
                <input type="text" name="empName">
            </td>
        </tr>
        <tr>
            <td>age</td>
            <td>
                <input type="text" name="age">
            </td>
        </tr>
        <tr>
            <td>gender</td>
            <td>
                <input type="radio" name="gender" value="女"><input type="radio" name="gender" value="男"></td>
        </tr>
        <tr>
            <td>email</td>
            <td>
                <input type="text" name="email">
            </td>
        </tr>
        <tr>
            <td colspan="4">
                <input type="submit" value="add">
            </td>
        </tr>
    </table>
</form>

</body>
</html>

src/main/webapp/WEB-INF/templates/employee_update.html

<!DOCTYPE html>
<!--suppress ALL-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Employee Delete</title>
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<form th:action="@{'/employee/'+${page.pageNum}}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="empId" th:value="${employee.empId}">
    <table>
        <tr>
            <th colspan="2">update employee</th>
        </tr>
        <tr>
            <td>empName</td>
            <td>
                <input type="text" name="empName" th:value="${employee.empName}">
            </td>
        </tr>
        <tr>
            <td>age</td>
            <td>
                <input type="text" name="age" th:value="${employee.age}">
            </td>
        </tr>
        <tr>
            <td>gender</td>
            <td>
                <input type="radio" name="gender" value="女" th:field="${employee.gender}"><input type="radio" name="gender" value="男" th:field="${employee.gender}"></td>
        </tr>
        <tr>
            <td>email</td>
            <td>
                <input type="text" name="email" th:value="${employee.email}">
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" th:value="update">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

你可能感兴趣的:(mybatis,spring,java)