Spring+SprinMVC+MyBatis配置方式简易模板代码Demo GitHub访问 ssm-tpl-cfg
创建数据库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;
<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.cfggroupId>
<artifactId>ssm-tpl-cfgartifactId>
<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>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>
dependencies>
project>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:config/applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:config/spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<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>characterEncodingFilterparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
<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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:config/db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="maxWait" value="${jdbc.maxWait}"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="filters" value="wall,stat" />
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*DAO.xml"/>
<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.tpl.ssm.cfg.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
bean>
<context:component-scan base-package="com.tpl.ssm.cfg.service"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
<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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.tpl.ssm.cfg.controller"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:resources mapping="/js/" location="/js/**"/>
<mvc:resources mapping="/css/" location="/css/**"/>
<mvc:resources mapping="/images/" location="/images/**"/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971520"/>
<property name="defaultEncoding" value="UTF-8"/>
bean>
beans>
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"/>
<setting name="cacheEnabled" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<typeAliases>
<package name="com.tpl.ssm.cfg.entity"/>
typeAliases>
configuration>
# 连接数据库的url地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
# 加载的类的驱动
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
# 数据库用户名
jdbc.username=root
jdbc.password=root
# 初始化连接大小
jdbc.initialSize=10
# 连接池最大使用连接数量
jdbc.maxActive=500
# 连接池最小空闲
jdbc.minIdle=10
# 获取连接最大等待时间
jdbc.maxWait=60000
package com.tpl.ssm.cfg.entity;
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;
/**
* 扩展字段
*/
@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;
}
}
package com.tpl.ssm.cfg.controller;
import com.tpl.ssm.cfg.entity.TestEntity;
import com.tpl.ssm.cfg.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.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(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/";
}
}
package com.tpl.ssm.cfg.service;
import com.tpl.ssm.cfg.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.cfg.service.impl;
import com.tpl.ssm.cfg.dao.TestDAO;
import com.tpl.ssm.cfg.entity.TestEntity;
import com.tpl.ssm.cfg.service.TestService;
import com.tpl.ssm.cfg.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());
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;
}
}
package com.tpl.ssm.cfg.dao;
import com.tpl.ssm.cfg.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.cfg.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.cfg.entity.TestEntity" resultType="com.tpl.ssm.cfg.entity.TestEntity">
<include refid="baseSelect"/>
FROM `ssm-tpl-cfg`
WHERE
1 = 1
<include refid="baseWhere"/>
select>
<select id="singleTest" parameterType="com.tpl.ssm.cfg.entity.TestEntity" resultType="com.tpl.ssm.cfg.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.cfg.entity.TestEntity">
INSERT INTO `ssm-tpl-cfg`(id, name)
VALUES (#{id}, #{name})
insert>
<update id="updateTest" parameterType="com.tpl.ssm.cfg.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.cfg.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>
package com.tpl.ssm.cfg.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 主键生成器
*
* https://blog.csdn.net/weixin_42871989/article/details/100133736
* 本类用于获取mysql全局自增主键,格式为
* 时间戳(yyMMddHHmm) + 5 位自增,自增范围根据配置获取(也可以加上秒yyMMddHHmmss)
*/
public class MajorKeyUtil {
private static final DateFormat df = new SimpleDateFormat("yyMMddHHmm");//主键时间戳
private static final int MAX_SEQ = 0; // 计数位最大值
private static final int RESET_SEQ = 99999; //计数位重置初始值(可以自行设置)
private static final AtomicInteger seq = new AtomicInteger(RESET_SEQ); //计数器
/**
* 生成全局自增主键,字符串类型
*
* @return 生成的主键
*/
public static String getSeq() {
seq.compareAndSet(MAX_SEQ, RESET_SEQ); //判断是否进行重置
return df.format(new Date()) + String.format("%05d", seq.incrementAndGet());
}
/**
* 生成全局自增主键,long类型
*
* @return 生成的主键
*/
public static Long idSeq() {
String str = getSeq();
return Long.parseLong(str);
}
}
<%--
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>
访问 http://127.0.0.1:8080/ssm_tpl_cfg/test/
一个简易基于配置的增删改查就实现了