SSM整合_年轻人的第一个增删改查_基础环境搭建
SSM整合_年轻人的第一个增删改查_查找
SSM整合_年轻人的第一个增删改查_新增
SSM整合_年轻人的第一个增删改查_修改
SSM整合_年轻人的第一个增删改查_删除
GitHub:https://github.com/say-hey/ssm_crud
Gitee:https://gitee.com/say-hey/ssm_crud
有用吗?对于学完Spring、SpringMVC、Mybatis还无从下手的同学来说这是一个很好引子。对于正在学习同一个案例的同学,可能解决一些问题。对于需要这个案例的同学可以直接获取。
有什么?:xml配置文件编写,引入一个简单的前端框架,使用MyBatis Generator逆向工程生成一些代码,使用框架简单快速搭建一个页面,好用的分页工具PageHelper,简单的前后端分离,发送ajax请求,利用json传递数据,增、删、改、查的简单实现。
简单吗?内容很简单,涉及Java代码不多,但是对于新手来说,最困难的部分是各种环境搭建、配置文件、版本冲突,如果能够根据错误提示动手解决,那就是一大进步。
怎么学?如果有时间可以在B站搜索:ssm整合crud,雷丰阳讲的。如果想看到每个功能的实现过程和源码,可以在这里学习,每个步骤都有注释。也可以作为复习快速浏览。
什么样?如下图:
- 安装设置java、maven、mysql
- 设置编辑器UTF-8,Tomcat编码UTF-8
- 待补充
ssm_crud
src
main
java
resources
webapp
WEB-INF
views
web.xml
index.jsp
pom.xml
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>com.ssmgroupId>
<artifactId>ssm_crudartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>ssm_crud Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.2.1.RELEASEversion>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.3version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.3version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.18version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiterartifactId>
<version>RELEASEversion>
<scope>compilescope>
dependency>
dependencies>
<build>
<finalName>ssm_crudfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
Bootstrap官网下载:起步 · Bootstrap v3 中文文档 | Bootstrap 中文网 (bootcss.com)
webapp目录下创建static目录,将bootstrap-3.3.7-dist
整个文件夹放入
在static目录下引入jquery-1.12.4.js
文件
在webapp目录下的index.jsp
中使用,只需要查看文档添加相应的class
样式
ssm_crud
src
main
java
resources
webapp
static
bootstrap-3.3.7-dist
jquery-1.12.4.js
WEB-INF
views
web.xml
index.jsp
pom.xml
<%-- 解决乱码 --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Hello World!
将index.jsp
在Tomcat中运行
根据Tomcat设置端口访问http://localhost:[端口号]/index.jsp
会出现带有Bootstrap样式的按钮
DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<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>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter>
<filter-name>hiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter>
<filter-name>formContentFilterfilter-name>
<filter-class>org.springframework.web.filter.FormContentFilterfilter-class>
filter>
<filter-mapping>
<filter-name>formContentFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter-mapping>
<filter-name>hiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>springDispatcherServletservlet-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>springDispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<context:property-placeholder location="classpath:dbconfig.properties"/>
<bean id="pooledDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.jdbcUrl}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="pooledDataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao">property>
bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
<constructor-arg name="executorType" value="BATCH"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="pooledDataSource">property>
bean>
<aop:config>
<aop:pointcut expression="execution(* com.ssm.service..*(..))" id="txPoint"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
<tx:method name="get*" read-only="true"/>
tx:attributes>
tx:advice>
beans>
#c3p0数据源配置,使用jdbc前缀防止冲突
#jdbc.driver=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
#jdbc.user=root
#jdbc.password=123456
#druid数据源配置,mysql 5和mysql 8配置信息不同
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456
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>
<typeAliases>
<package name="com.ssm.bean"/>
typeAliases>
configuration>
<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.ssm" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
beans>
ssm_crud
,两个表tbl_dept
、tbl_emp
-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`dept_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for tbl_emp
-- ----------------------------
DROP TABLE IF EXISTS `tbl_emp`;
CREATE TABLE `tbl_emp` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`d_id` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`emp_id`) USING BTREE,
INDEX `fk_emp_dept`(`d_id`) USING BTREE,
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1036 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
根据现有的数据库结构生成对象的JavaBean、Dao接口、Mapper.xml等
在ssm_crud根目录下创建mbg.xml配置文件
DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<commentGenerator>
<property name="javaFileEncoding" value="UTF-8"/>
<property name="suppressAllComments" value="true"/>
commentGenerator>
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false"
userId="root" password="123456"/>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
javaTypeResolver>
<javaModelGenerator targetPackage="com.ssm.bean"
targetProject="src\main\java"/>
<sqlMapGenerator targetPackage="mapper"
targetProject="src\main\resources"/>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.ssm.dao" targetProject="src\main\java"/>
<table tableName="tbl_emp" domainObjectName="Employee">table>
<table tableName="tbl_dept" domainObjectName="Department">table>
context>
generatorConfiguration>
在com.ssm.test
包中任意创建一个测试方法,然后运行
/**
* MyBatis Generator逆向工程
*/
public class MBGTest {
public static void main(String[] args) throws InvalidConfigurationException, IOException, XMLParserException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
之后项目自动生成文件,主要分三部分
自动生成的功能不能满足指定的查询条件,所以需要修改
实现一条sql完成联表查询,在逆向工程的基础上,需要修改以下地方
JavaBean
Department
package com.ssm.bean;
public class Department {
private Integer deptId;
private String deptName;
//如果用了构造器,一定要写无参构造器
public Department() {
super();
}
public Department(Integer deptId, String deptName) {
super();
this.deptId = deptId;
this.deptName = deptName;
}
//get/set/toString
}
Employee
package com.ssm.bean;
public class Employee {
private Integer empId;
private String empName;
private String gender;
private String email;
private Integer dId;
// 增加联合查询
private Department department;
// 如果用了构造器,一定要写无参构造器
public Employee() {
super();
}
// 不加Department的属性
public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
super();
this.empId = empId;
this.empName = empName;
this.gender = gender;
this.email = email;
this.dId = dId;
}
// get/set/toString
}
Dao
EmployeeMapper
public interface EmployeeMapper {
//...
//新增两个查询方法,用于联合查询
List<Employee> selectByExampleWithDept(EmployeeExample example);
Employee selectByPrimaryKeyWithDept(Integer empId);
}
Mapper
EmployeeMapper.xml
<mapper namespace="com.ssm.dao.EmployeeMapper">
<sql id="WithDept_Column_List">
e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
sql>
<resultMap type="com.ssm.bean.Employee" id="WithDeptResultMap">
<id column="emp_id" jdbcType="INTEGER" property="empId" />
<result column="emp_name" jdbcType="VARCHAR" property="empName" />
<result column="gender" jdbcType="CHAR" property="gender" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="d_id" jdbcType="INTEGER" property="dId" />
<association property="department" javaType="com.ssm.bean.Department">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
association>
resultMap>
<select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
select
<if test="distinct">
distinct
if>
<include refid="WithDept_Column_List"/>
from tbl_emp e
left join tbl_dept d
on e.d_id = d.dept_id
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
if>
order by e.emp_id
select>
<select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
select
<include refid="WithDept_Column_List"/>
from tbl_emp e
left join tbl_dept d
on e.d_id = d.dept_id
where emp_id = #{empId,jdbcType=INTEGER}
select>
mapper>
在com.ssm.test
中任意创建测试类,测试sql连接并添加数据
//如果您想在测试中使用Spring测试框架功能(例如)@MockBean,则必须使用@ExtendWith(SpringExtension.class)。它取代了不推荐使用的JUnit4@RunWith(SpringJUnit4ClassRunner.class)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
//批量sqlSession
@Autowired
SqlSessionTemplate sqlSessionTemplate;
@Test
public void test(){
//Employee employee = employeeMapper.selectByPrimaryKeyWithDept(1);
//System.out.println(employee);
//1.插入部门
// departmentMapper.insertSelective(new Department(null, "开发部"));
// departmentMapper.insertSelective(new Department(null, "测试部"));
//2.插入员工
// employeeMapper.insertSelective(new Employee(null, "Tom", "M", "[email protected]", 1));
//3.批量插入
//使用sqlSessionTemplat可以实现批量,不使用就不是
EmployeeMapper eMapperTemplat = sqlSessionTemplate.getMapper(EmployeeMapper.class);
for(int i = 0 ; i <= 1000 ; i++) {
String uuid = UUID.randomUUID().toString().substring(0, 5) + i;
//这里继续使用employeeMapper就不行
//employeeMapper.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
//使用employeeMapperTemplat批量插入
eMapperTemplat.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
}
}
}
到目前为止,Spring、SpringMVC、MyBatis都已经配置完成,各功能可以连通,可以进行编写增删改查的代码了。目前目录结构如下
ssm_crud
src
main
java
com.ssm.bean
Department.java
EmployeeExample.java
Employee.java
DepartmentExample.java
com.ssm.dao
EmployeeMapper.java
DepartmentMapper.java
com.ssm.service
com.ssm.controller
com.ssm.test
MapperTest.java
MBGTest.java
com.ssm.utils
resources
mapper
DepartmentMapper.xml
EmployeeMapper.xml
applicationContext.xml
dbconfig.properties
mybatis-config.xml
springmvc.xml
webapp
static
bootstrap-3.3.7-dist
jquery-1.12.4.js
WEB-INF
views
web.xml
index.jsp
pom.xml
mbg.xml