一个关于SSM整合的增删改查
用到的技术 :springMVC spring mybatis mysql maven idea
pom文件:
在maven中pom文件中需要引用常见的一些jar包,可以在 maven仓库中进行搜索需要引用jar包的坐标
maven仓库网址:https://mvnrepository.com/
常用的 jar:
spring webmvc
spring aspect 切面 编程
spring jdbc 版本对应
mybatis
mybatis spring 整合包
c3p0 数据库连接池
MySql Connertor/J 数据库连接驱动
返回json字符串需要的jacksonjar包
数据绑定校验 hibernate validator JSR303校验
jstl
servlet API
junit 单元测试
Mybatis Generator Core mybatis的逆向工程
springtest 测试模块
applicationContext.xml
在这个里面可以写:
<!--Spring的配置文件,这就要是配置与业务逻辑有关-->
<!--数据源,事务控制,-->
<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>
<context:property-placeholder location=“classpath:dbconfig.properties” />指向的文件:dbconfig.properties内容:
以mysql为例:
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/数据库名
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=数据库用户名
jdbc.password=数据库密码
<!--配置mybatis整合-->
<bean id="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>
<!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有dao接口的实现,加入到ioc容器中 -->
<property name="basePackage" value="com.atguigu.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>
<!-- ===============事务控制的配置 ================-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--控制住数据源 -->
<property name="dataSource" ref="pooledDataSource"></property>
</bean>
<!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) -->
<aop:config>
<!-- 切入点表达式 -->
<aop:pointcut expression="execution(* com.atguigu.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开始的所有方法 这样配置的话所有以get开头的方法都是只读的-->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
指定mybatis全局配置文件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>
<!--bean起别名-->
<typeAliases>
<package name="com.atguigu.bean"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--分页参数合理化 -->
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
指定mybatis,mapper文件的位置,可以将所有的mapper写在 一个 mapper文件夹内,使用property 标签
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
引入PageHelper插件进行分页
例如展示所有的用户信息带分页
@RequestMapping("/emps")
@ResponseBody
public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn) {
//引入PageHelper插件进行分页
PageHelper.startPage(pn, 5);//这个5是指一页中有5条数据
List<Employee> empList = employeeService.getEmpAll();
//封装了详细的信息
//固定显示五个页码
PageInfo page = new PageInfo(empList, 5);
//Msg是提前定义好的一个类
//这个类方便向前台返回数值并且方便在返回的数据中添再加一些数据,例如对象或者对象集合
return Msg.success().add("pageInfo", page);
}
Msg类
package com.atguigu.bean;
import java.util.HashMap;
import java.util.Map;
/**
* 通用的返回类
* @author Zhm
* @date 2020/3/17 11:05
**/
public class Msg {
private int code; //100-成功 200-失败
private String msg; //提示信息
private Map<String,Object> entend = new HashMap<String, Object>(); //用户给浏览器返回的信息
/**
* 成功
* @return result
*/
public static Msg success(){
Msg result = new Msg();
result.setCode(100);
result.setMsg("成功");
return result;
}
/**
* 失败
* @return result
*/
public static Msg fail(){
Msg result = new Msg();
result.setCode(200);
result.setMsg("失败");
return result;
}
/**
* 添加方法
* @param key
* @param value
* @return
*/
public Msg add(String key,Object value){
this.getEntend().put(key, value);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getEntend() {
return entend;
}
public void setEntend(Map<String, Object> entend) {
this.entend = entend;
}
}
JSR303校验
这个校验是指前台传到后台的一些数据进行校验,例如邮箱格式,用户名格式
1.先在实体类中进行规定参数的格式:
例如员工实体类中员工名和邮箱:
//用户名
@Pattern(regexp = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})",message = "用户名必须是6-16位数字或字母或者2-5位中文")
private String empName;
//邮箱
@Pattern(regexp = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",message = "邮箱格式不正确")
private String eamil;
2.在Controller层进行判断
/**
* 验证用户名是否已经存在
* 验证用户名时候格式是否合格
* @param empName
* @return
*/
@RequestMapping("/checkuser")
@ResponseBody
public Msg getByEmpName(String empName) {
String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
if (empName.matches(regx)) {
boolean b = employeeService.getByEmpName(empName);
if (b) {
return Msg.success();
} else {
return Msg.fail().add("va_msg", "用户名已经存在");
}
} else {
return Msg.fail().add("va_msg", "用户名必须是6-16位数字或字母或者2-5位中文");
}
}
逆向工程
导入jar包:Mybatis Generator Core
创建配置文件: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">
<!--这个是true的话生成的代码没有注释-->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置数据库连接 -->
<jdbcConnection driverClass="数据库驱动"
connectionURL="jdbc:mysql://localhost:3306/数据库名" userId="数据库用户名"
password="数据密码">
</jdbcConnection>
<!---->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定javaBean生成的位置 -->
<javaModelGenerator targetPackage="com.atguigu.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接口生成的位置,mapper接口 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.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>
再写一个测试类用于生产逆向工程
MbgTest
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;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
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);
}
}
web.xml
启动Spring的容器
springmvc的前端控制器,拦截所有请求
字符编码过滤器,一定要放在所有过滤器之前
使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求
解决PUT请求不会被自动封装为map
<?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"
id="WebApp_ID" 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>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<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>
<!--解决PUT请求不会被自动封装为map-->
<filter>
<filter-name>HttpPutFormContentFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
本文详细介绍SSM(SpringMVC、Spring、MyBatis)框架整合的步骤与技巧,包括pom配置、数据库连接、事务控制及逆向工程等内容,旨在帮助开发者快速掌握SSM框架的应用。
1740

被折叠的 条评论
为什么被折叠?



