Spring+SpringMVC+Mybatis实现增删改查–(一)SSM环境的搭建及整合
整个项目的功能点:
整个项目的技术点
一、Spring+Spring MVC+Mybatis项目基础环境搭建
1、创建一个maven project工程
2.在pom.xml中引入项目所依赖的包
spring、springmvc、mybatis、数据库连接池、驱动包以及其他包
具体的包:spring-webmvc spring-jdbc spring-aspects
mybatis mybatis-spring c3p0 mysql-connector
jstl javax.servlet-api junit mybatis-generator-core spring-test
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.0</modelVersion>
<groupId>com.lcz</groupId>
<artifactId>ssm_crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- 引入项目依赖的jar包 -->
<dependencies>
<!-- 引入spring mvc及spring -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Spring面向切面编程 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- Mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- Mybatis整合spring的整合 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 数据库连接池、驱动 -->
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- 其他包 jstl servlet-api junit -->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MBG -->
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- spring test -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.引入bootstrap框架
(1)下载bootstrap框架
https://v3.bootcss.com/getting-started/#download
下载用于生产环境的BootStrap的。
(2)在项目的webapp下新建一个static文件夹里,在里面新建一个js文件夹用来存放从网上下载的jquery.js,同时在static文件夹里粘贴下载好的bootstrap文件夹。
(3)如何界面中引入bootstrap框架
<!-- 引入样式 -->
<script type="text/javascript" src="static/js/jquery-3.3.1.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
4.编写ssm整合的关键配置文件
web.xml application.xml springmvc.xml mybatis_config.xml
(1).webapp/WEB-INF/web.xml
<!– 1.启动spring的容器 –>
可以通过快捷键alt+/,选择contextloadlistener,修改<param-value>中为applicationContext.xml的路径
<!– 2.springmvc的前端控制器,拦截所有请求 –>
可以通过快捷键alt+/,选择dispatcherServlet,然后修改<param-value>中为spring_mvc.xml
<!– 3.字符编码过滤器,一定要放在所有过滤器之前 –>
CharacterEncodingFilter 通过ctrl+shift+t快捷键搜索前面的包,打开,并进行配置
<!– 4..使用Rest风格的URI,将页面普通的post请求转换为指定delete或者post请求–>
HiddenHttpMethodFilter通过ctrl+shift+t快捷键搜索前面的包,打开,并进行配置
具体的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<!-- 1.启动spring的容器 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 2.springmvc的前端控制器,拦截所有请求 -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring_mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 3.字符编码过滤器,一定要放在所有过滤器之前 -->
<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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 4..使用Rest风格的URI,将页面普通的post请求转换为指定delete或者post请求-->
<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>
</web-app>
(2).spring_mvc.xml
a.src/main/resources新建一个spring bean configuration file。
这里要注意要想出现上述配置文件,需要在Help->Eclipse Marketplace中安装好STS(Spring Tool Suit),然后在eclipse中preferences中general->editors->file associations进行配置
将spring config editor设置为default,为第一个显示,即设置完毕。
b.设置spring_mvc.xml
<!– 1.配置扫描器,让其只扫描包含@Controller的 –>
<!– 2.配置视图解析器,方便页面返回 –>
<!– 3.标准配置 –>
<!– 将springmvc不能处理的请求交给tomcat –>
<!– 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax请求,映射动态请求 –>
添加链接时,可以快速的在视图中通过namespaces来添加如下图
具体的配置如下:
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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-4.3.xsd">
<!-- spring MVC的配置文件,包含网站跳转逻辑的控制,配置-->
<!-- 1.配置扫描器,让其只扫描包含@Controller的 -->
<context:component-scan base-package="com.lcz" use-default-filters="true">
<!-- 只扫描控制器 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 2.配置视图解析器,方便页面返回 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 3.标准配置 -->
<!-- 将springmvc不能处理的请求交给tomcat -->
<mvc:default-servlet-handler/>
<!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax请求,映射动态请求 -->
<mvc:annotation-driven/>
</beans>
(3)applicationContext.xml(同上一步建立步骤)
<!– 1.数据源的配置 –>
<!– 2.业务逻辑组件扫描(除了扫描控制器) –>
<!–3.配置和mybatis的整合 –>
<!– 4.配置扫描器,将mybatis接口的实现加入到ioc容器中 –>
<!– 5.事务控制的配置 –>
<!– 6.开启基于注解的事务,使用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:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- spring的配置文件,这里主要配置和业务逻辑有关的 -->
<!-- 数据源,事务控制,xxx -->
<!-- 1.数据源的配置 -->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 2.业务逻辑组件扫描(除了扫描控制器) -->
<context:component-scan base-package="com.lcz">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--3.配置和mybatis的整合 -->
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定mybatis全局配置文件的配置 -->
<property name="configLocation" value="classpath:mybatis_config.xml"></property>
<!-- 指定数据源 -->
<property name="dataSource" ref="pooledDataSource"></property>
<!-- 指定mybatis,mapper文件的位置 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 4.配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描所有的dao接口的实现,加入到ioc容器中 -->
<property name="basePackage" value="com.lcz.crud.dao"></property>
</bean>
<!-- 配置一个可以执行批量的sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
<constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
<!-- 5.事务控制的配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 控制数据源 -->
<property name="dataSource" ref="pooledDataSource"></property>
</bean>
<!-- 6.开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式的) -->
<aop:config>
<!-- 切入点表达式 -->
<aop:pointcut expression="execution(* com.lcz.crud.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="*"/>
<!-- 以get开始的所有方法 -->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- spring配置文件的核心店(数据源、mybatis整合,事务控制) -->
</beans>
(4)mybatis_config.xml
新建一个.xml文件,在其中设置好全局配置
<?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>
<!-- 驼峰命名法 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 类型别名 -->
<typeAliases>
<package name="com.lcz.crud.bean"/>
</typeAliases>
</configuration>
4.数据库的编写
在数据库中建立一个ssm_crud数据库并建立两个表tbl_dept及tbl_emp
(1).tbl_dept表的设计规则
(2).tbl_empt表的设计规则
(3).tbl_empt表的关联规则
设置外键
(4)下面给出建表语句
tbl_dept表的建表语句
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50721
Source Host : localhost:3306
Source Database : ssm_crud
Target Server Type : MYSQL
Target Server Version : 50721
File Encoding : 65001
Date: 2018-06-08 07:19:49
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- 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) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_dept
-- ----------------------------
INSERT INTO `tbl_dept` VALUES ('1', '开发部');
INSERT INTO `tbl_dept` VALUES ('2', '测试部');
tbl_emp表的建表语句
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50721
Source Host : localhost:3306
Source Database : ssm_crud
Target Server Type : MYSQL
Target Server Version : 50721
File Encoding : 65001
Date: 2018-06-08 07:19:57
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- 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) NOT NULL,
`gender` char(1) NOT NULL,
`email` varchar(255) NOT NULL,
`d_id` int(11) NOT NULL,
PRIMARY KEY (`emp_id`),
KEY `fk_emp_dept` (`d_id`),
CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tbl_emp
-- ----------------------------
INSERT INTO `tbl_emp` VALUES ('1', 'Mali', 'F', '[email protected]', '1');
INSERT INTO `tbl_emp` VALUES ('2', 'Mark', 'M', '[email protected]', '1');
5.mybatis generator逆向工程的编写
使用mybatis逆向工程可以直接根据数据库中数据表生成bean以及mapper
mybatis generator
(1)在pom.xml中导包
mybatis-generator-core
(2)在项目下新建mbg.xml
打开网址http://www.mybatis.org/generator/configreference/xmlconfig.html
找到XML Configuration Reference然后复制粘贴到我们新建的mbg.xml中
然后修改配置信息,配置好数据库连接信息,指定javabean的生成位置、指定sql映射文件生成的位置、指定dao接口生成的位置,table指定每个表的生成策略。
源码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!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">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javabean生成的位置 -->
<javaModelGenerator targetPackage="com.lcz.crud.bean" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 指定dap接口生成的位置,mapper接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.lcz.crud.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- table指定每个表的生成策略 -->
<table tableName="tbl_emp" domainObjectName="Employee"></table>
<table tableName="tbl_dept" domainObjectName="Department"></table>
</context>
</generatorConfiguration>
(3)逆向工程的运行
运行之前先建立好各个包
然后在com.lcz.crud.test这个包中新建一个MBGTest的类用来运行。
运行代码可见刚才的Mybatis generator的官网的连接中
修改好文件位置,运行即可。
源码如下:
package com.lcz.crud.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MBGTest {
public static void main(String[] args) throws Exception {
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);
}
}
(4)运行结果
运行之后可见bean包及dao包以及resource下的mapper文件自动生成了。这里由于项目关系,所以对mapper文件下的EmployeeMapper.xml文件进行了修改,新增了一个关联查询,可以查询employee的时候同时查询出department。
6.导入spring test
通过spring test来测试上述的CRUD是否能够运行
(1)导入springtest包
(2)@ContextConfiguration指定spring配置文件的位置
(3)直接autowired的组件
package com.lcz.crud.test;
import java.util.UUID;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lcz.crud.bean.Department;
import com.lcz.crud.bean.Employee;
import com.lcz.crud.dao.DepartmentMapper;
import com.lcz.crud.dao.EmployeeMapper;
/**
* 测试dao层的工作
* @author LvChaoZhang
* 推荐spring的项目就可以使用spring的单元测试,可以自动注入我们需要的空间
* 1.导入springtest包
* 2.@ContextConfiguration指定spring配置文件的位置
* 3.直接autowired的组件
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentmapper;
@Autowired
EmployeeMapper employmapper;
@Autowired
SqlSession sqlsession;
/**
* 测试DepartmentMapper
*/
@SuppressWarnings("resource")
@Test
public void testCRUD() {
// //1.创建spring ioc容器
// ApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
// //2.从容器中获取mapper
// Department bean = ioc.getBean(Department.class);
System.out.println(departmentmapper);
//1.插入几个部门
// departmentmapper.insertSelective(new Department(null,"开发部"));
// departmentmapper.insertSelective(new Department(null,"测试部"));
//2.插入员工
//employmapper.insertSelective(new Employee(null,"jack","M","[email protected]",1));
//3.批量插入多个员工,批量,使用可以执行批量操作的sqlsession
/*for()
employmapper.insertSelective(new Employee(null,"jack","M","[email protected]",1));
*/
EmployeeMapper mapper = sqlsession.getMapper(EmployeeMapper.class);
for(int i=0;i<1000;i++) {
String uid=UUID.randomUUID().toString().substring(0, 5)+""+i;
mapper.insertSelective(new Employee(null,uid,"M",uid+"@lcz.com",1));
}
System.out.println("批量执行完毕!");
}
}
7.项目链接
github地址:点击打开链接
csdn地址:点击打开链接