Spring+SprinMVC+MyBatis注解方式简易模板

Spring+SprinMVC+MyBatis注解方式简易模板代码Demo GitHub访问 ssm-tpl-anno

一、数据准备

创建数据库test,执行下方SQL创建表ssm-tpl-cfg

/*
 Navicat Premium Data Transfer

 Source Server         : 127.0.0.1
 Source Server Type    : MySQL
 Source Server Version : 80030
 Source Host           : 127.0.0.1:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80030
 File Encoding         : 65001

 Date: 17/10/2022 00:52:07
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for ssm-tpl-cfg
-- ----------------------------
DROP TABLE IF EXISTS `ssm-tpl-cfg`;
CREATE TABLE `ssm-tpl-cfg` (
  `id` bigint NOT NULL COMMENT '主键编号',
  `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '测试名称',
  PRIMARY KEY (`id`)
) COMMENT '初始SSM表结构数据' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ----------------------------
-- Records of ssm-tpl-cfg
-- ----------------------------
BEGIN;
INSERT INTO `ssm-tpl-cfg` (`id`, `name`) VALUES (2210162246100000, '左翰林');
INSERT INTO `ssm-tpl-cfg` (`id`, `name`) VALUES (2210162257100000, '刘卓神');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

二、代码实现

2.1 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.tpl.ssm.annogroupId>
    <artifactId>ssm-tpl-annoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

    <properties>
        <spring_version>5.1.18.RELEASEspring_version>
        <jackson_version>2.9.7jackson_version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-beansartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-expressionartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-messagingartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring_version}version>
        dependency>
        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-apiartifactId>
            <version>7.0version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plusartifactId>
            <version>3.4.2version>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-annotationartifactId>
            <version>3.4.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.16version>
        dependency>
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>2.8.5version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.15.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>2.15.2version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-annotationsartifactId>
            <version>2.15.2version>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>2.0.7version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.36version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.7.0version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.7.0version>
        dependency>
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>commons-langgroupId>
            <artifactId>commons-langartifactId>
            <version>2.6version>
        dependency>
        <dependency>
            <groupId>commons-collectionsgroupId>
            <artifactId>commons-collectionsartifactId>
            <version>3.2.2version>
        dependency>
        <dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.9.4version>
        dependency>
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.4version>
        dependency>
        <dependency>
            <groupId>commons-poolgroupId>
            <artifactId>commons-poolartifactId>
            <version>1.6version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.4version>
        dependency>
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.11.0version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjrtartifactId>
            <version>1.9.7version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.7version>
        dependency>
        <dependency>
            <groupId>com.google.code.findbugsgroupId>
            <artifactId>annotationsartifactId>
            <version>2.0.0version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2groupId>
            <artifactId>fastjson2artifactId>
            <version>2.0.25version>
        dependency>
    dependencies>
project>

2.2 Spring和Mybatis配置

package com.tpl.ssm.anno.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * Spring配置类
 *
 * 
 * 
 */
@ComponentScan(basePackages = {"com.tpl.ssm.anno.service"}, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Controller.class)
})
@EnableTransactionManagement
@Configuration
public class SpringConfig {

    private static final Logger logger = LoggerFactory.getLogger(SpringConfig.class);

    /*
     * 
     * 
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     *     
     * 
     */
    @Bean(name = "dataSource")
    public DruidDataSource druidDataSource() {
        // 基本属性 url、user、password
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");

        // 配置初始化大小、最小、最大
        druidDataSource.setInitialSize(10);
        druidDataSource.setMinIdle(10);
        druidDataSource.setMaxActive(50);

        // 配置获取连接等待超时的时间
        druidDataSource.setMaxWait(60000);
        // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);

        // 配置一个连接在池中最小生存的时间,单位是毫秒
        druidDataSource.setMinEvictableIdleTimeMillis(300000);

        druidDataSource.setValidationQuery("SELECT 1");
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);

        // 打开PSCache,并且指定每个连接上PSCache的大小
        // 如果用Oracle,则把poolPreparedStatements配置为true,
        // mysql可以配置为false。
        druidDataSource.setPoolPreparedStatements(true);
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

        // 配置监控统计拦截的filters
        try {
            druidDataSource.setFilters("wall,stat");
        } catch (SQLException e) {
            logger.error("配置监控统计拦截的filters error: ", e);
        }
        return druidDataSource;
    }

    /*
     * 
     * 
     *     
     *     
     *     
     *     
     *     
     *     
     * 
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setMapperLocations(resolveMapperLocations());
        sqlSessionFactory.setDataSource(druidDataSource());
        /*
         * 
         * 
         * 
         *
         *     
         *     
         *         
         *         
         *         
         *         
         *         
         *         
         *     
         *
         *     
         *     
         *         
         *     
         * 
         */
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisConfiguration.setCacheEnabled(true);
        mybatisConfiguration.setLogImpl(StdOutImpl.class);
        mybatisConfiguration.getTypeAliasRegistry().registerAliases("com.tpl.ssm.anno.entity");

        sqlSessionFactory.setConfiguration(mybatisConfiguration);
        return sqlSessionFactory;
    }

    // https://wenku.baidu.com/view/1b9ade1640323968011ca300a6c30c225901f0c2.html
    public Resource[] resolveMapperLocations() {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath:mapper/*DAO.xml");
        List<Resource> resources = new ArrayList<>();
        for (String mapperLocation : mapperLocations) {
            Resource[] mappers = new Resource[0];
            try {
                mappers = resolver.getResources(mapperLocation);
            } catch (IOException e) {
                e.printStackTrace();
            }
            resources.addAll(Arrays.asList(mappers));
        }
        return resources.toArray(new Resource[0]);
    }

    /*
     * 
     * 
     *     
     *     
     * 
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.tpl.ssm.anno.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }

    /* 事务管理器配置
     * 
     *     
     * 
     */
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}

2.3 SpringMVC配置

package com.tpl.ssm.anno.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/* 开启controller注解支持
 * 注意事项请参考:http://jinnianshilongnian.iteye.com/blog/1762632
 *
 * 
 */
@ComponentScan(basePackages = {
        "com.tpl.ssm.anno.controller"
}, includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Controller.class),
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.web.bind.annotation.ControllerAdvice.class)
}, useDefaultFilters = false)
@EnableWebMvc
@Configuration
// 
// @Import(value = {SpringMvcXxxConfig.class})
public class SpringMVCConfig implements WebMvcConfigurer {

    /* 
     * 
     *     
     *     
     * 
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        resolver.setPrefix("/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    /* 
     * 
     * 
     * 
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/").addResourceLocations("/js/**");
        registry.addResourceHandler("/css/").addResourceLocations("/css/**");
        registry.addResourceHandler("/images/").addResourceLocations("/images/**");
    }

    // 文件解析器
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // maxUploadSizePerFile:单个文件大小限制(byte)
        // maxUploadSize:整个请求大小限制(byte)
        commonsMultipartResolver.setMaxUploadSizePerFile(10 * 1024 * 1024); // 10M
        commonsMultipartResolver.setMaxUploadSize(100 * 1024 * 1024); // 100M
        return commonsMultipartResolver;
    }

}

2.4 web.xml配置

package com.tpl.ssm.anno.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * Web应用启动入口
 * 

* * */ public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { // 父容器配置 AnnotationConfigWebApplicationContext springCtx = new AnnotationConfigWebApplicationContext(); springCtx.setDisplayName("ssm-tpl-anno"); // 部署应用的名称 ssm-tpl-anno /* * * * contextConfigLocation * * classpath:spring-config.xml * * * * org.springframework.web.context.ContextLoaderListener * * */ springCtx.register(SpringConfig.class); // 通过监听器加载配置信息 servletContext.addListener(new ContextLoaderListener(springCtx)); /* 可以使用RequestContextHolder.currentRequestAttributes() 获取到请求的attr * * org.springframework.web.context.request.RequestContextListener * */ servletContext.addListener(org.springframework.web.context.request.RequestContextListener.class); // 子容器配置 AnnotationConfigWebApplicationContext mvcCtx = new AnnotationConfigWebApplicationContext(); /* * * * springMVC * org.springframework.web.servlet.DispatcherServlet * * contextConfigLocation * classpath:spring-mvc.xml * * 1 * true * * * springMVC * / * * */ mvcCtx.register(SpringMVCConfig.class); ServletRegistration.Dynamic servlet = servletContext.addServlet( "DispatcherServlet", new DispatcherServlet(mvcCtx)); servlet.setLoadOnStartup(1); servlet.setAsyncSupported(true); servlet.addMapping("/"); /* * * * CharacterEncodingFilter * org.springframework.web.filter.CharacterEncodingFilter * true * * encoding * UTF-8 * * * forceEncoding * true * * * * CharacterEncodingFilter * /* * * */ FilterRegistration.Dynamic encodingFilter = servletContext.addFilter( "CharacterEncodingFilter", new CharacterEncodingFilter("UTF-8", true)); encodingFilter.setAsyncSupported(true); encodingFilter.addMappingForUrlPatterns(null, false, "/*"); } }

2.5 Entity

package com.tpl.ssm.anno.entity;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 测试实体
 */
public class TestEntity {

    /**
     * 主键编号
     */
    private Long id;

    /**
     * 测试名称
     */
    private String name;

    private JSONObject flowImg;
    private String flowImgStr;


    /**
     * 扩展字段
     */
    @JsonIgnore
    @TableField(exist = false)
    private Map<String, Object> ext = new LinkedHashMap<>(5);

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, Object> getExt() {
        return ext;
    }

    public void setExt(Map<String, Object> ext) {
        this.ext = ext;
    }

    public JSONObject getFlowImg() {
        return flowImg;
    }

    public void setFlowImg(JSONObject flowImg) {
        this.flowImg = flowImg;
    }

    public String getFlowImgStr() {
        return flowImgStr;
    }

    public void setFlowImgStr(String flowImgStr) {
        this.flowImgStr = flowImgStr;
    }
}

2.6 Controller

package com.tpl.ssm.anno.controller;

import com.tpl.ssm.anno.entity.TestEntity;
import com.tpl.ssm.anno.service.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 1. Spring5.1.x -> jackson2.9.x
 * 2.The origin server did not find a current representation for the target resource
 * 原因是WEB-INF只能转发进去, 重定向是进不去的
 */
@Controller
@RequestMapping("/test")
public class TestController {

    private final TestService testService;

    public TestController(TestService testService) {
        this.testService = testService;
    }

    @GetMapping("/")
    public String listTests(TestEntity test, Model model) {
        List<TestEntity> tests = testService.listTests(test);
        model.addAttribute("tests", tests);
        return "test";
    }

    @PostMapping("/save")
    public String saveTest(@RequestBody TestEntity test) {
        testService.saveTest(test);
        return "redirect:/test/";
    }

    @PostMapping("/modify")
    public String modifyTest(TestEntity test) {
        testService.modifyTest(test);
        return "redirect:/test/";
    }

    @RequestMapping("/remove")
    public String removeTest(TestEntity test) {
        testService.removeTest(test);
        return "redirect:/test/";
    }

}

2.7 Service

package com.tpl.ssm.anno.service;

import com.tpl.ssm.anno.entity.TestEntity;

import java.util.List;

public interface TestService {

    /**
     * 测试集
     *
     * @param cond 查询条件
     * @return 测试集
     */
    public List<TestEntity> listTests(TestEntity cond);

    /**
     * 单一测试实体
     *
     * @param cond 查询条件
     * @return 测试实体
     */
    public TestEntity singleTest(TestEntity cond);

    /**
     * 新增测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean saveTest(TestEntity cond);

    /**
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean modifyTest(TestEntity cond);

    /**
     * 删除一条测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean removeTest(TestEntity cond);

    /**
     * 删除多条测试记录
     *
     * @param testIds 测试实体主键集
     * @return 受影响的条数
     */
    public boolean removeTests(List<Long> testIds);

}
package com.tpl.ssm.anno.service.impl;

import com.tpl.ssm.anno.dao.TestDAO;
import com.tpl.ssm.anno.entity.TestEntity;
import com.tpl.ssm.anno.service.TestService;
import com.tpl.ssm.anno.util.MajorKeyUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestServiceImpl implements TestService {

    private final TestDAO testDAO;

    public TestServiceImpl(TestDAO testDAO) {
        this.testDAO = testDAO;
    }

    @Override
    public List<TestEntity> listTests(TestEntity cond) {
        return testDAO.listTests(cond);
    }

    @Override
    public TestEntity singleTest(TestEntity cond) {
        return testDAO.singleTest(cond);
    }

    @Override
    public boolean saveTest(TestEntity cond) {
        cond.setId(MajorKeyUtil.idSeq());
        cond.setFlowImgStr(cond.getFlowImg().toString());
        return testDAO.insertTest(cond) > 0;
    }

    @Override
    public boolean modifyTest(TestEntity cond) {
        return testDAO.updateTest(cond) > 0;
    }

    @Override
    public boolean removeTest(TestEntity cond) {
        return testDAO.deleteTest(cond) > 0;
    }

    @Override
    public boolean removeTests(List<Long> testIds) {
        return testDAO.deleteTests(testIds) > 0;
    }
}

2.8 DAO

package com.tpl.ssm.anno.dao;

import com.tpl.ssm.anno.entity.TestEntity;

import java.util.List;

/**
 * 测试DAO
 * 

* 1.查询测试记录列表 - listTests * 2.查询单个测试记录 - singleTest * 3.新增测试记录 - insertTest * 4.修改测试记录 - updateTest * 5.删除测试记录 - deleteTest * 6.根据主键集删除测试记录 - deleteTests */ public interface TestDAO { /** * 测试集 * * @param cond 查询条件 * @return 测试集 */ public List<TestEntity> listTests(TestEntity cond); /** * 单一测试实体 * * @param cond 查询条件 * @return 测试实体 */ public TestEntity singleTest(TestEntity cond); /** * 新增测试记录 * * @param cond 查询条件 * @return 受影响的条数 */ public int insertTest(TestEntity cond); /** * @param cond 查询条件 * @return 受影响的条数 */ public int updateTest(TestEntity cond); /** * 删除一条测试记录 * * @param cond 查询条件 * @return 受影响的条数 */ public int deleteTest(TestEntity cond); /** * 删除多条测试记录 * * @param testIds 测试实体主键集 * @return 受影响的条数 */ public int deleteTests(List<Long> testIds); }


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tpl.ssm.anno.dao.TestDAO">

    
    <sql id="baseSelect">
        SELECT id, name
    sql>

    
    <sql id="baseWhere">
        <if test="id != null">
            AND id = #{id}
        if>
        <if test="name != null and name != ''">
            AND name like CONCAT('%', #{name})
        if>
    sql>

    
    <select id="listTests" parameterType="com.tpl.ssm.anno.entity.TestEntity" resultType="com.tpl.ssm.anno.entity.TestEntity">
        <include refid="baseSelect"/>
        FROM `ssm-tpl-cfg`
        WHERE
        1 = 1
        <include refid="baseWhere"/>
    select>

    
    <select id="singleTest" parameterType="com.tpl.ssm.anno.entity.TestEntity" resultType="com.tpl.ssm.anno.entity.TestEntity">
        <include refid="baseSelect"/>
        FROM `ssm-tpl-cfg`
        WHERE
        1 = 1
        <include refid="baseWhere"/>
        limit 1
    select>

    
    <insert id="insertTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        INSERT INTO `ssm-tpl-cfg`(id, name, flow_img)
        VALUES (#{id}, #{name}, #{flowImgStr})
    insert>

    
    <update id="updateTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        UPDATE `ssm-tpl-cfg`
        SET
        <if test="name != null and name != ''">
            name = #{name}
        if>
        WHERE id = #{id}
    update>

    
    <delete id="deleteTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        DELETE
        FROM `ssm-tpl-cfg`
        WHERE 1 = 1
        <include refid="baseWhere"/>
    delete>

    
    <delete id="deleteTests" parameterType="long">
        DELETE
        FROM `ssm-tpl-cfg`
        WHERE id in
        <foreach collection="item" open="(" separator="," close=")">
            #{item}
        foreach>
    delete>
mapper>

2.9 webapps/pages/test.jsp

<%--
  Created by IntelliJ IDEA.
  User: wangfeihu
  Date: 2022/10/16
  Time: 18:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>CRUD TESTtitle>
head>
<body>
<table>
    <c:forEach items="${tests}" var="test">
        <tr>
            <td>${test.id}td>
            <td>${test.name}td>
            <td>
                <button onclick="let modifyForms = document.getElementsByName('modifyForm'); modifyForms.forEach(item => item.style.display = 'none'); document.getElementById('form${test.id}').style.display = 'inline'">修改button>
                <button onclick="location.href='${pageContext.request.contextPath}/test/remove?id=${test.id}'">删除button>
            td>
            <td>
                <form id="form${test.id}" name="modifyForm" action="${pageContext.request.contextPath}/test/modify" method="post" style="display: none">
                    <input hidden name="id" value="${test.id}">
                    <input name="name" value="${test.name}">
                    <button type="submit">确认修改button>
                form>
            td>
        tr>
    c:forEach>
table>

<form action="${pageContext.request.contextPath}/test/save" method="post">
    <label>
        <input name="name" id="name" placeholder="请输入测试名称~">
    label>
    <button type="submit">提交button>
form>
body>
html>

2.10 配置项目访问路径

Spring+SprinMVC+MyBatis注解方式简易模板_第1张图片

三、访问测试

Spring+SprinMVC+MyBatis注解方式简易模板_第2张图片

一个简单的基于注解的增删改查就实现了

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