栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SSM框架整合 - 实现基本的CURD效果

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SSM框架整合 - 实现基本的CURD效果

文章目录
  • 1. 搭建环境
  • 2. 查询
  • 3. 新增
  • 4. 修改
  • 5. 删除
  • 6. 小结

1. 搭建环境
  1. 创建基础Maven工程, 导入项目所需要的依赖


    4.0.0

    org.example
    SSM-curd
    1.0-SNAPSHOT

    
        11
        11
    


    
    

        
        
            org.springframework
            spring-webmvc
            5.3.9
        

        
        
            org.springframework
            spring-jdbc
            5.3.9
        

        
        
            org.springframework
            spring-aspects
            5.3.9
        

        

        
        
            org.mybatis
            mybatis
            3.5.7
        

        
            org.mybatis
            mybatis-spring
            2.0.6
        
        
        
            org.mybatis.generator
            mybatis-generator
            1.4.0
        
        
            org.mybatis.generator
            mybatis-generator-maven-plugin
            1.4.0
        


        
        
            com.alibaba
            druid
            1.0.9
        

        
        
            mysql
            mysql-connector-java
            8.0.26
        

        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        

        
            javax.servlet.jsp
            jsp-api
            2.1
        

        
            javax.servlet
            jstl
            1.2
        

        
        
            junit
            junit
            4.13.1
            test
        
        
    

  1. 引入前端相关框架, 这里使用的是BootStrap和Jquery, 将其存放在webapp下的static文件夹中
    注意: bootstrap的js文件要在js文件后引入,
  2. 编写整合的关键文件(web.xml、Spring、SpringMVC、MyBatis
    )
    web.xml



    

    
        contextConfigLocation
        classpath:spring.xml
    

    
        
        org.springframework.web.context.ContextLoaderListener
    


    
    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springMVC.xml
        
        1
    
    
        dispatcherServlet
        /
    
    
    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceResponseEncoding
            true
        
    
    
        characterEncodingFilter
        /*
    

    
    
    
        hiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    

    
        hiddenHttpMethodFilter
        /*
    


编写SpringMVC的配置文件

```html



    
    
        
        
        
    

    

    
        
        
    

    
    

    
    

    
    
    

创建包结构

编写Spring的配置文件(核心: 扫描、数据源、事务控制、和Mybatis的整合、)
注意名称空间的引入(tx、aop、context、)




    

    
        
        
    

    
    
    
    
        
        
        
        
    

    
    
        
        
        

        
        


    

    
    
        
        
    

    
    
        
        
    

    
    
    
        
        

        
        

    

    
    
        
            
            

            

        
    

    

编写Mybatis配置文件(通过逆向工程生成代码)

附: 数据库建库和测试数据

CREATE DATAbase db2;
USE db2;
DROP TABLE t_emp;
DROP TABLE t_dept;

CREATE TABLE t_dept(
   id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   dname VARCHAR(20) NOT NULL
);

CREATE TABLE t_emp(
   emp_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
   emp_name VARCHAR(10) NOT NULL,
   gender CHAR(1) NOT NULL,
   email VARCHAR(20),
   dept_id INT NOT NULL,
   CONSTRAINT fk_emp_dept_id FOREIGN KEY(dept_id) REFERENCES t_dept(id)
);
INSERT INTO t_dept VALUES(NULL,"采购部");
INSERT INTO t_dept VALUES(NULL,"人事部");
INSERT INTO t_dept VALUES(NULL,"保安部");

INSERT INTO t_emp VALUES(NULL,"niko","男","1135552060@qq.com",1);
INSERT INTO t_emp VALUES(NULL,"luna","女","123456789@qq.com",3);

SELECT * FROM t_dept;
SELECt * FROM t_emp;

SELECt
  e.*,d.`dname`
FROM t_emp e LEFT JOIN t_dept d ON e.dept_id = d.id;

注意: 在IDEA中需要通过测试方法来执行mgb代码, 如果出现主类无法加载的情况, 删除掉工程中的iml文件 刷新maven即可

先编写主配置文件, 基础配置




    
        
        
    
    
    
        
        
    

编写逆向工程MGB.xml配置文件





    
    
        
        

        
            
        
         
        
        
            
            
        
        
        
            
        
        
        
        
            
        
        
        
        

编写测试代码

package com.atguigu.test;

import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MGB {
    @Test
    public void testMgb() throws XMLParserException, IOException, InvalidConfigurationException, SQLException, InterruptedException {
        List generatorWarnings = new ArrayList();
        File file = new File("mgb.xml");
        ConfigurationParser cp = new ConfigurationParser(generatorWarnings);
        Configuration config = cp.parseConfiguration(file);
        DefaultShellCallback shellCallback = new DefaultShellCallback(true);
        MyBatisGenerator generator = new MyBatisGenerator(config,shellCallback,generatorWarnings);
        generator.generate(null);
    }
}

执行即可, 目录结构如下

对Mapper文件进行修改增加联合查询功能
示例: 我想在查emp表的同时通过d_id来得到deptName的信息

实体类Emp

EmpMapper.xml



    
    
    
    
    
    
      
      
    
  
  
  
    e.*,d.`dname`
  
  
  
    select
    
      distinct
    
    
    from t_emp e left join t_dept d on e.dept_id = d.dept_id
    
      
    
    
      order by ${orderByClause}
    
  
  

搭建Spring单元测试环境
引入依赖


    org.springframework
    spring-test
    5.3.9

使用注解指定spring文件的位置

@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig(locations = {"classpath:spring.xml"})
public class MapperTest {

    @Autowired
    private DeptMapper dm;
    @Test
    public void testQuery(){
        int result = dm.insertSelective(new Dept(null, "采购部"));
        System.out.println(result);
    }
}
2. 查询

创建首页转发, 当访问首页时发送/emps请到员工列表页面

引入分页插件pagehelper的依赖

  
        
            com.github.pagehelper
            pagehelper
            5.0.0
        

创建Service层

@Service
public class EmpService {
    @Autowired
    private EmpMapper empMapper;

    public List getEmpAll(){
        return empMapper.selectByExampleWithDept(null);
    }
}

创建Controller层

@Controller
public class EmpController {
    @Autowired
    private EmpService empService;

    @RequestMapping("/emps")
    public String getEmp(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model){

        // 引入分页插件pageHelper
        // pn 页码  pageSize 每页容量
        PageHelper.startPage(pn,5);
        // startPage后面紧跟的就是一个分页查询
        List empAll = empService.getEmpAll();
        // 包装查询后的结果

        // 这个5是连续分页的页数
        PageInfo pageInfo = new PageInfo(empAll,5);

        model.addAttribute("pageInfo",pageInfo);

        return "views/list";
    }

}

员工列表前端

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/10/1
  Time: 18:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    员工列表
    
    
    
    



   

SSM-CURD

empid empName gender email deptName 操作
${emp.empId} ${emp.empName} ${emp.gender} ${emp.email} ${emp.dept.dname}
当前第${pageInfo.pageNum}页,总共${pageInfo.pages}页,共${pageInfo.total}条记录

效果

改造
使用Ajax返回分页数据
逻辑

  1. index.jsp页面直接发出Ajax请求进行员工分页数据的查询
  2. 服务器将查出的数据, 以Json字符串的形式返回给浏览器
  3. 浏览器收到js字符串, 可以使用Js对json进行解析, 通过dom的增删改来改变网页
  4. 返回json, 实现客户端的无关性

编写通用的返回JSON数据的类Msg

package com.atguigu.curd.bean;

import java.util.HashMap;
import java.util.Map;

public class Msg {
    // 返回JSON数据的类

    private int code;
    // 状态码

    private String msg;
    // 提示信息

    // 用户要返回给浏览器的数据
    private Map extend = new HashMap();

    public static Msg success(){
        Msg result = new Msg();
        result.setCode(100);
        result.setMsg("处理成功~");

        return result;
    }

    public static Msg fail(){
        Msg result = new Msg();
        result.setCode(200);
        result.setMsg("处理失败~");

        return result;
    }

    public Msg add(String key,Object value){
        this.getExtend().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 getExtend() {
        return extend;
    }

    public void setExtend(Map extend) {
        this.extend = extend;
    }
}

引入用于JSON转换的依赖

 
            com.fasterxml.jackson.core
            jackson-databind
            2.12.4
        

        
            com.fasterxml.jackson.core
            jackson-core
            2.12.4
        

注意在springMVC的配置文件中开启注解驱动

修改Controller层控制器方法

 @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmp(@RequestParam(value = "pn",defaultValue = "1") Integer pn){
        // 引入分页插件pageHelper
        // pn 页码  pageSize 每页容量
        PageHelper.startPage(pn,5);
        // startPage后面紧跟的就是一个分页查询
        List empAll = empService.getEmpAll();
        // 包装查询后的结果

        // 这个5是连续分页的页数
        PageInfo pageInfo = new PageInfo(empAll,5);

        return Msg.success().add("pageInfo",pageInfo);
    }

启动项目, 效果如下

修改前端页面, 通过Js的DOM增删改来显示表格数据

员工页面

SSM-CURD

empid empName gender email deptName 操作

操作DOM来为表格、分页条等中添加数据