一、项目简介
1、SSM-CRUD
- SSM
Spring+SpringMVC+MyBatis
- CRUD
Create(创建)
Retrieve(查询)
Update(修改)
Delete(删除)
2、功能点
- 分页
- 数据校验
- jquery前端校验+JSR303后端校验
- ajax
- REST风格的URI;使用HTTP协议请求方式的动词,来表示对资源的请求操作【GET(查询)、POST(新增)、PUT(修改)、DELETE(删除)】
3、技术点
-
基础框架—SSM(Spring+SpringMVC+MyBatis)
-
项目的依赖管理—Maven
-
逆向工程—MyBatis Generator
二、基础环境搭建
1、创建一个Maven工程
2、设置maven配置文件
- 配置maven仓库镜像位置,在settings.xml文件中
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
<profile>
<id>jdk-1.7</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.7</jdk>
</activation>
<repositories>
<repository>
<id>jdk17</id>
<name>Repository for JDK 1.7 builds</name>
<url>http://www.myhost.com/maven/jdk17</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
3、引入项目依赖的jar包
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<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.achang</groupId>
<artifactId>ssm_crud</artifactId>
<version>1.0</version>
<name>ssm_crud</name>
<packaging>war</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.6.2</junit.version>
</properties>
<!--引入項目依賴的jar包-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- spring-面向切面 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!--mybatis整合spring适配包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>MysqL</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--servletAPI-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--单元测试JUnit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</build>
</project>
4、引入bootstrap前端框架
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<!--引入jquery-->
<script type="text/javascript" src="static/js/jquery-1.7.2.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>
<body>
<button type="button" class="btn btn-success">按钮</button>
</body>
</html>
5、编写ssm整合的关键配置文件
①dbconfig.properties:
jdbc_driverClassName=com.MysqL.jdbc.Driver
jdbc_url=jdbc:MysqL://localhost:3306/ssm_crud
jdbc_password=00000
jdbc_username=root
②web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--1、启动spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--配置spring配置文件地址-->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--2、springmvc的前端控制器,拦截所有请求-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.dispatcherServlet</servlet-class>
<init-param>
<!--配置mvc的配置文件地址-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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或者put请求-->
<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>
.
③spring的applicationContext.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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--Spring配置文件,主要配置和业务逻辑有关的-->
<!--数据源,事务控制,...-->
<context:component-scan base-package="com.achang">
<!--不扫控制器-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入外部配置文件-->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/dbconfig.properties"/>
</bean>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="druidDataSource">
<property name="driverClassName" value="${jdbc_driverClassName}"/>
<property name="url" value="${jdbc_url}"/>
<property name="password" value="${jdbc_password}"/>
<property name="username" value="${jdbc_username}"/>
</bean>
<!--=======配置mybatis的整合=========-->
<bean class="org.mybatis.spring.sqlSessionfactorybean" id="sessionFactory">
<!--指定mybatis全局配置文件的位置-->
<property name="configLocation" value="classpath:mybatis_config.xml"/>
<!--指定数据源-->
<property name="dataSource" ref="druidDataSource"/>
<!--指定mybatis,mapper文件的位置-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--配置扫描器,将mybatis接口的实现加入到ioc容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有dao下的接口的实现,加入ioc容器-->
<property name="basePackage" value="com.achang.dao"/>
</bean>
<!--====================================-->
<!--事务控制管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<!--控制数据源-->
<property name="dataSource" ref="druidDataSource"/>
</bean>
<!--事务控制配置-->
<!--开启基于注解的事务,或使用xml配置形式的事务(重要的使用xml配置形式)-->
<aop:config>
<!--切入点表达式,service下的所有包的所有类都切入使用事务控制-->
<aop:pointcut id="txPoint" expression="execution(* com.achang.service..*(..))"/>
<!--配置事务增强-->
<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整合spring、事务控制-->
</beans>
.
④springmvc的applicationContext-mvc.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: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">
<!--springmvc配置文件,包含网址跳转逻辑控制,配置-->
<!--1、扫描包,并禁用默认过滤规则-->
<context:component-scan base-package="com.achang" use-default-filters="false">
<!--只扫描标了@Controller注解的控制器-->
<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/view"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3、两个标准配置,打开外挂-->
<!--处理静态文件,将mvc不能处理的交给tomcat服务器处理-->
<mvc:default-servlet-handler/>
<!--处理动态文件;能支持springmvc更高级的功能,JSR303校验,快捷ajax,映射动态请求-->
<mvc:annotation-driven/>
</beans>
.
⑤mybatis_config.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.achang.bean"/>
</typeAliases>
</configuration>
.
⑥逆向工程MBG.xml:
<?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="00000">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--指定javaBean生成的位置-->
<javaModelGenerator targetPackage="com.achang.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>
<!--指定dao接口生成的位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.achang.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--指定每个表的生成策略-->
<table tableName="tbl_emp" domainObjectName="Employee"/>
<table tableName="tbl_dept" domainObjectName="Department"/>
</context>
</generatorConfiguration>
public class MBGTest {
@Test
public void testMBG() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("D:\\JavaStudy\\SSM_CRUD\\ssm_crud\\src\\main\\resources\\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);
}
}
6、测试mapper功能是否实现
①使用原生单元测试
@Test
public void testCRUD(){
原生spring获取容器mapper方式
//1、创建springIOC容器
ApplicationContext ioc = new ClasspathXmlApplicationContext("applicationContext.xml");
//2、从容器中获取mapper
ioc.getBean(DepartmentMapper.class);
}
②使用springTest单元测试
* 使用Spring的单元测试
* 1、导入springTest单元测试模块
* 2、@ContextConfiguration指定spring配置文件的位置
* 3、直接autowired要使用的组件即可
pom.xml
<!--SpringTest单元测试模块-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)//指定运行哪个单元测试模块,使用spring的test单元测试模块
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})//指定spring配置文件的位置
public class MapperTest {
//通过以上使用spring单元测试模块,就可以直接将此加入ioc容器
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Test
public void testCRUD(){
//通过springTest模块获取mapper方式
System.out.println(departmentMapper);//org.apache.ibatis.binding.MapperProxy@2ca923bb
}
}
③插入部门
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Test
public void testCRUD(){
//1、插入几个部门
departmentMapper.insertSelective(new Department(null,"开发部"));
departmentMapper.insertSelective(new Department(null,"测试部"));
}
}
④插入员工
//2、生成员工数据,测试员工插入
employeeMapper.insert(new Employee(null,"张飞","M","zhangfei@achang.com",1));
⑤批量插入
方式一、通过for循环批量插入
方式一、
for (){
employeeMapper.insert(new Employee(null,"张飞","M","zhangfei@achang.com",1));
}
方式二:通过在ioc容器中设置一个batch批量插入的sqlSession
在ioc容器中配置可批量插入batch类型的sqlSession
<!--配置一个可以执行批量的sqlSession-->
<bean class="org.mybatis.spring.sqlSessionTemplate" id="sqlSession">
<constructor-arg name="sqlSessionFactory" ref="sessionFactory"/>
<constructor-arg name="executorType" value="BATCH"/>
</bean>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
@Autowired
DepartmentMapper departmentMapper;
@Autowired
EmployeeMapper employeeMapper;
@Autowired
sqlSession sqlSession;//批量插入
public void testCRUD(){
//方式二、通过在ioc容器中设置一个batch批量插入的sqlSession
//只发送一次带有条数的sql请求插入
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
for (int i = 0; i < 1000; i++) {
String s = UUID.randomUUID().toString().substring(0, 5)+i;
mapper.insertSelective(new Employee(null,s ,"M",s+"@achang.com",1));
}
System.out.println("批量插入完成");
}
}
⑥修改员工
//修改员工
employeeMapper.updateByPrimaryKey(new Employee(3,"赵云","M","zhaoyun@achang.com",2));
⑦删除员工
//删除员工
employeeMapper.deleteByPrimaryKey(2);
⑧数据库截图
- tbl_dept
- tbl_emp
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。