title: SSM入门
categories: SSM
tags: SSM
搭建简单的SSM项目
什么是SSM
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。
SSM的基本构成是什么?
1. Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。 Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。
2. SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
3. mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。
SSM框架的好处有哪些呢
-
减少编码
好的开发框架编写了大量的基础功能,程序员将工作重心放到业务逻辑上的实现。
比如spring 简化了java程序对数据库的访问,提高了数据库的访问效率和稳定性,程序员只需要写好sql就行了。
规范性,重用性
开发框架使用了很多设计模式,比如mvc,在编写代码的时候程序员可以遵循mvc的模式,编写Controller,entity,view 对应的代码。
易扩展,易维护
mybatis 实现了对数据库的封装,当程序从oracle转向mysql时,不需要改动太多的地方,就能很方便的完成转变。
规范化编码,对维护性来说,方便了后续人员对代码的理解和修改。
SSM当然具备以上三种优势,尤其是从spring mvc 转变spring boot之后,约定大于配置,进一步简化了繁琐的配置工作,编写代码如丝滑般顺滑。
下面废话不多说说,我将开始第一个ssm项目的搭建工作
- 第一部需要搭建ssm框架说需要的配置资源文件,这些都是可以一步用一万步的,也正因为这些资源文件的繁琐多且容易出错,导致现在SSM逐渐没落,SpringBoot这样的框架逐渐成为主流
mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTDConfig3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--注册别名-->
<typeAliases>
<package name="com.bookstore.commons.beans"/>
</typeAliases>
<!--注册映射文件-->
<mappers >
<package name="com.bookstore.**.dao"/>
</mappers>
</configuration>
Spring-datasource
<?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"
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">
<!--加载属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--注册数据源,druid-->
<bean id="myDataSource" class=" com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
SpringMvc
<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">
<!-- 注册组件扫描器,扫描所有handler包下的注册@controller -->
<context:component-scan base-package="com.bookstore.**.handler"/>
<!-- 注解驱动-->
<mvc:annotation-driven/>
<!--处理静态文件 -->
<mvc:default-servlet-handler/>
<!-- Multipart解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/admin/**"/>
<mvc:exclude-mapping path="/admin/images/**"/>
<mvc:exclude-mapping path="/admin/css/**"/>
<mvc:exclude-mapping path="/admin/js/**"/>
<mvc:exclude-mapping path="/admin/jquery/**"/>
<bean class="com.bookstore.admin.Interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!--异常解析器-->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="/jsp/error.jsp"/>
<!– 获取异常的类型–>
<property name="exceptionAttribute" value="ex"/>
<!– 根据异常的类型不同。到达不同的页面–>
<!– <property name="excludedExceptions">
<props>
<prop key="AAAA">/jsp/aaa.jsp</prop>
<prop key="BBBB">/jsp/bbbb.jsp</prop>
</props>
</property>–>
</bean>-->
</beans>
Spring-Mybatis整合配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!--注册sqlsessionfactory-->
<bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--生成dao代理对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bookstore.**.dao"/>
<property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
</bean>
</beans>
Spring-service*整合
<?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"
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">
<!--注册组件扫描器,扫描所以service包下的@service-->
<context:component-scan base-package="com.bookstore.**.service"/>
</beans>
Spring-tx事务
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!-- 注册平台事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myDataSource"/>
</bean>
<!-- 注册事务通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- 注册指定连接点-->
<tx:attributes>
<tx:method name="CreateOrder" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="remove*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="modify*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="find*" propagation="REQUIRED" isolation="DEFAULT" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- AOP配置-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* *..service.*.*(..))"/>
</aop:config>
</beans>
jdbc数据库连接
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///bookstore
jdbc.username=root
jdbc.password=123456
- 是对ssm配置的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.aynu</groupId>
<artifactId>bookstore</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>bookstore Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12
-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!--
https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina
-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>9.0.30</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-core
-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jcl</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.mybatis/mybatis-spring
-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--
https://mvnrepository.com/artifact/mysql/mysql-connector-java
-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.9.124.ALL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>bookstore</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
</project>
-
下面需要编写框架需要的bean实体类,在这里我就用了我上一个书城项目的原型来说明
下面实体类里包含user表里的各种元素,然后利用idea自动生成下路SET,GET方法和输出
package com.bookstore.commons.beans;
/**
* @author 杨宇翔
* @version 1.0
* @date 2020/4/07 11:10
*/
import java.util.Date;
public class User {
private Integer id;
private String username;
private String password;
private String gender;
private String email;
private String telephone;
private String introduce;
private String activeCode;
private int state;
private String role;
private Date registTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getActiveCode() {
return activeCode;
}
public void setActiveCode(String activeCode) {
this.activeCode = activeCode;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Date getRegistTime() {
return registTime;
}
public void setRegistTime(Date registTime) {
this.registTime = registTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
", telephone='" + telephone + '\'' +
", introduce='" + introduce + '\'' +
", activeCode='" + activeCode + '\'' +
", state=" + state +
", role='" + role + '\'' +
", registTime=" + registTime +
'}';
}
}
- 这一次我们开始入手三层框架的处理器层,也就是SpringMvc层,这一层里定义了框架所需要的各种方法,通过执行方法成功最终返回前台的JSP页面,顾名思义MVC就是Model,View和Controller的缩写,这一层就是视图框架和控制的整合
//用户激活
@RequestMapping("/activeUser")
public String activeUser(String activeCode) {
System.out.println("激活码为:" + activeCode);
int rows = userService.activeUser(activeCode);
if (rows > 0) {
//如果有参数需要再请求域内共享 就不需要加redirect
return "redirect:/client/activesuccess.jsp";
} else {
return "redirect:/client/activeFail.jsp";
}
}
//检查邮箱是否被占用
@RequestMapping("/findEmail")
@ResponseBody
public String findEmail(String email) {
// System.out.println("注册的邮箱"+email);
User user = userService.findEmail(email);
if (user != null) {
return "EXIST";
} else {
return "OK";
}
}
//检查会员名是否被占用
@RequestMapping("/findUsername")
@ResponseBody
public String findUsername(String username) {
User user = userService.findUsername(username);
if (user != null) {
return "EXIST";
} else {
return "OK";
}
}
//我的账户
@RequestMapping("/myAccount")
public String myAccount(HttpSession session,HttpServletRequest request) {
//获取session中的登陆用户信息
User login_user = (User) session.getAttribute("login_user");
if (login_user == null) {//用户未登录
//自动登陆能否成功 调用自动登陆方法
login_user = autologin(request);
if (login_user != null){
//如果自动登陆成功,返回的login_user就不为空
//自动登陆成功,把登录用户信息放到session
session.setAttribute("login_user",login_user);
return "/client/myAccount.jsp";
}
return "/client/login.jsp"; //点击我的账户到登陆页面
} else { //用户已登陆
return "/client/myAccount.jsp"; //显示我的账户信息
}
}
//用户登陆和验证激活
@RequestMapping("/login")
public String login(User user, String remember,String autologin, HttpServletRequest request, HttpSession session, HttpServletResponse response) {
//查询用户名和密码是否存在
User login_user = userService.findUserByLogin(user);
if (login_user != null) {//如果用户名和密码正确
if (login_user.getState() == 1){//如果用户已激活,则登陆成功
if ("1".equals(autologin)){
//保存用户名和密码到cookie
addCookie(autologin,user,request,response);
}else if ("1".equals(remember)){
//记住用户名,把用户名保存在cookie
addCookie(autologin,user,request,response);
}
session.setAttribute("login_user", login_user);
return "/client/myAccount.jsp";
} else {//用户未激活
request.setAttribute("login_error", "用户名未激活,请激活后使用");
return "/client/login.jsp";
}
} else{
request.setAttribute("login_error", "用户名或密码错误,请重新登陆");
return "/client/login.jsp";
}
}
//用户退出
@RequestMapping("/logout")
public String logout(HttpSession session, Model model,HttpServletRequest request,HttpServletResponse response){
//从session中移除登录用户
session.removeAttribute("login_user");
//删除用户名
Cookie cookie1 = new Cookie("bookstore_username",null);
cookie1.setMaxAge(0);
cookie1.setPath(request.getContextPath()+"/");
response.addCookie(cookie1);
model.addAttribute("login_error","用户退出成功,请重新登陆");
//删除密码
Cookie cookie2 = new Cookie("bookstore_password",null);
cookie2.setMaxAge(0);
cookie2.setPath(request.getContextPath()+"/");
response.addCookie(cookie2);
model.addAttribute("login_error","用户退出成功,请重新登陆");
return "/client/login.jsp";
}
- 第二层是Spring层也就是service层,这一层把上一层controller定义的方法通过接口传递过来
package com.bookstore.client.user.service;
/**
* @author 杨宇翔
* @version 1.0
* @date 2020/4/07 11:23
*/
import com.bookstore.commons.beans.Order;
import com.bookstore.commons.beans.OrderItem;
import com.bookstore.commons.beans.User;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
public interface IUserService {
int addUser(User user, HttpServletRequest request);
int activeUser(String activeCode);
User findEmail(String email);
User findUsername(String username);
User findUserByLogin(User user);
int modifyUser(User user);
List<Order> findOrderByUser(Integer id);
List<OrderItem> findOrderItemById(String id);
void removeOrderById(String id, String flag);
}
- 如果是接口就必须要要有实现类,于是还要在这一层定义一个实现类,有时候为了保证事物的原子性一致性,可以在这一层增加一些横向的事务
package com.bookstore.client.user.service;
/**
* @author 杨宇翔
* @version 1.0
* @date 2020/4/07 11:23
*/
@Service
public class UserServiceImpl implements IUserService {
@Resource
IUserDao userDao;
@Override
public int addUser(User user, HttpServletRequest request) {
String emailMsg = "感谢您使用网上书城,请点击<a href='http://localhost:8080"+request.getContextPath()+"/client/user/activeUser?activeCode="+user.getActiveCode()+"'>激活</a>后使用!";
try {
MailUtil.sendMail(user.getEmail(),emailMsg);
} catch (MessagingException e) {
e.printStackTrace();
}
return userDao.insertUser(user);
}
@Override
public int activeUser(String activeCode) {
return userDao.activeUser(activeCode);
}
@Override
public User findEmail(String email) {
return userDao.selectEmail(email);
}
@Override
public User findUsername(String username) {
return userDao.selectUsername(username);
}
@Override
public User findUserByLogin(User user) {
return userDao.selectUserByLogin(user);
}
@Override
public int modifyUser(User user) {
return userDao.updateUser(user);
}
@Override
public List<Order> findOrderByUser(Integer id) {
return userDao.selectOrderByUser(id);
}
@Override
public List<OrderItem> findOrderItemById(String id) {
return userDao.selectOrderItemById(id);
}
@Override
public void removeOrderById(String id, String flag) {
//先加上商品库存 再删除订单等 防止 删除订单后 查询不到需要被加回库存的id
if (flag == null){
List<OrderItem> items = userDao.selectOrderItemById(id);
//加回库存
for (OrderItem item:items) {
userDao.updateProductnum(item);
}
}
//删除订单和订单项
userDao.deleteOrderById(id);
userDao.deleteOrderItemById(id);
}
}
- 最后一层就是Dao层也就是Mybatis层,在这里需要通过接口传递上一层service的方法,然后编写SQL语句,通过sql语句完成我们说需要的功能,比如最简单的CURD
package com.bookstore.client.user.dao;
/**
* @author 杨宇翔
* @version 1.0
* @date 2020/4/07 11:23
*/
import com.bookstore.commons.beans.Order;
import com.bookstore.commons.beans.OrderItem;
import com.bookstore.commons.beans.User;
import java.util.List;
public interface IUserDao {
int insertUser(User user);
int activeUser(String activeCode);
User selectEmail(String email);
User selectUsername(String username);
User selectUserByLogin(User user);
int updateUser(User user);
List<Order> selectOrderByUser(Integer id);
List<OrderItem> selectOrderItemById(String id);
void deleteOrderById(String id);
void deleteOrderItemById(String id);
void updateProductnum(OrderItem item);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bookstore.client.user.dao.IUserDao">
<!--注册用户-->
<insert id="insertUser">
insert into user (username,password,email,gender,telephone,introduce,activeCode)
values (#{username},#{password},#{email},#{gender},#{telephone},#{introduce},#{activeCode})
</insert>
<!--激活就是把状态0修改为1-->
<update id="activeUser">
update user set state = 1
where activeCode = #{activeCode}
</update>
<!--查询邮箱是否已被使用-->
<select id="selectEmail" resultType="User">
select * from user where email = #{email}
</select>
<!--查询会员名是否被占用-->
<select id="selectUsername" resultType="User">
select * from user where username = #{username}
</select>
<!--查询登录用户-->
<select id="selectUserByLogin" resultType="User">
select * from user where username = #{username} and password = #{password}
</select>
<!--修改用户信息-->
<update id="updateUser">
update user set password = #{password},gender = #{gender},telephone = #{telephone} where id = #{id}
</update>
以上就是SSM框架的基本流程,当然我贴出的示例代码都是不完整的,毕竟连前台页面都没有,我只是说出了SSM框架的基本思想,有了这种是思想后就很容易上手其他的项目,当然现在SSM已经不是大势所趋,SpringBoot和SpringCloud这种微服务架构才是近几年的大势,但是无论学习什么一定要学好基础,了解道原理,才能更深层的学习
下一篇我会详细介绍SSN框架的一些常用的注解,方便学习
网友评论