SSM整合_年轻人的第一个增删改查_基础环境搭建


写在前面






GitHub:https://github.com/say-hey/ssm_crud
Gitee:https://gitee.com/say-hey/ssm_crud

??有用吗?对于学完Spring、SpringMVC、Mybatis还无从下手的同学来说这是一个很好引子。对于正在学习同一个案例的同学,可能解决一些问题。对于需要这个案例的同学可以直接获取。

??有什么?xml配置文件编写,引入一个简单的前端框架,使用MyBatis Generator逆向工程生成一些代码,使用框架简单快速搭建一个页面,好用的分页工具PageHelper,简单的前后端分离,发送ajax请求,利用json传递数据,增、删、改、查的简单实现。

??简单吗?内容很简单,涉及Java代码不多,但是对于新手来说,最困难的部分是各种环境搭建、配置文件、版本冲突,如果能够根据错误提示动手解决,那就是一大进步。

??怎么学?如果有时间可以在B站搜索:ssm整合crud,雷丰阳讲的。如果想看到每个功能的实现过程和源码,可以在这里学习,每个步骤都有注释。也可以作为复习快速浏览。

??什么样?如下图:

image
image
image
image
image
image

1、基础环境搭建

  1. 安装设置java、maven、mysql
  2. 设置编辑器UTF-8,Tomcat编码UTF-8
  3. 待补充

1. 创建Maven工程

  • 不同编译器创建工程稍有不同,大致目录结构
ssm_crud
    src
        main
        	java
        	resources
        	webapp
                WEB-INF
                	views
                	web.xml
                index.jsp
	pom.xml

2. 引入依赖jar

pom.xml

  • 目前的依赖只保证基本功能,后续使用其他功能需要再引入依赖
<?xml version="1.0" encoding="UTF-8"?>


    4.0.0

    com.ssm
    ssm_crud
    1.0-SNAPSHOT
    war

    ssm_crud Maven Webapp
    
    http://www.example.com

    
        UTF-8
        1.8
        1.8
    

    
    
    
        
        
            org.springframework
            spring-webmvc
            5.2.1.RELEASE
        
        
        
            org.springframework
            spring-jdbc
            5.2.1.RELEASE
        
        
        
            org.springframework
            spring-aspects
            5.2.1.RELEASE
        
        
        
        
            org.springframework
            spring-test
            5.2.1.RELEASE
            provided
        

        
        
        
            org.mybatis
            mybatis
            3.5.3
        
        
        
            org.mybatis
            mybatis-spring
            2.0.3
        

        
        
        
        
        
        
        
        

        
        
            com.alibaba
            druid
            1.2.8
        

        
        
            mysql
            mysql-connector-java
            
            8.0.18
        

        
        
            jstl
            jstl
            1.2
        
        
        
        
            javax.servlet
            javax.servlet-api
            4.0.1
            provided
        
        
        
            junit
            junit
            4.11
            test
        
        
        
            org.junit.jupiter
            junit-jupiter
            RELEASE
            compile
        
    
    
    
        ssm_crud
        
            
                
                    maven-clean-plugin
                    3.1.0
                
                
                
                    maven-resources-plugin
                    3.0.2
                
                
                    maven-compiler-plugin
                    3.8.0
                
                
                    maven-surefire-plugin
                    2.22.1
                
                
                    maven-war-plugin
                    3.2.2
                
                
                    maven-install-plugin
                    2.5.2
                
                
                    maven-deploy-plugin
                    2.8.2
                
            
        
    


3. 引入Bootstrap前端框架

  • Bootstrap官网下载:起步 · Bootstrap v3 中文文档 | Bootstrap 中文网 (bootcss.com)

  • webapp目录下创建static目录,将bootstrap-3.3.7-dist整个文件夹放入

  • 在static目录下引入jquery-1.12.4.js文件

  • 在webapp目录下的index.jsp中使用,只需要查看文档添加相应的class样式

    ssm_crud
        src
            main
            	java
            	resources
                webapp
                	static
                		bootstrap-3.3.7-dist
                		jquery-1.12.4.js
                    WEB-INF
                    	views
                        web.xml
                    index.jsp
    	pom.xml
    
    <%-- 解决乱码 --%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    
    
    
        <script src="static/jquery-1.12.4.js"></script>
        <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
        
    
    
    

    Hello World!

  • index.jsp在Tomcat中运行

  • 根据Tomcat设置端口访问http://localhost:[端口号]/index.jsp

  • 会出现带有Bootstrap样式的按钮

4. SSM整合配置文件

  • 配置文件是到目前为止,后续使用功能再添加
  • 虽然后面SpringBoot、SpringCloud配置文件变少了,但配置文件有助于理解框架的结构和功能
  • 使用不同Spring版本,部分配置文件可能不同,下面是Spring 5

web.xml



    
    Archetype Created Web Application
    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
        
            encoding
            UTF-8
        
        
        
            forceRequestEncoding
            true
        
        
            forceResponseEncoding
            true
        
    


    
    
        hiddenHttpMethodFilter
        org.springframework.web.filter.HiddenHttpMethodFilter
    
    
    
    
        formContentFilter
        org.springframework.web.filter.FormContentFilter
    
    
        formContentFilter
        /*
    
    
        characterEncodingFilter
        /*
    
    
        hiddenHttpMethodFilter
        /*
    

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
    
        springDispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            
            classpath:springmvc.xml
        
        1
    
    
    
        springDispatcherServlet
        /
    

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

    
    

    
    
        
    


    
    
    
    
    
    
    
    
    
    
    
        
        
        
        
    

    
    
        
        
        
        
        
        
    

    
    
        
        
    

    
    
        
        
        
    

    
    
        
    

    
    
        
        
        
        
    

    
    
    
        
            
            
            
            
        
    

dbconfig.properties

#c3p0数据源配置,使用jdbc前缀防止冲突
#jdbc.driver=com.mysql.cj.jdbc.Driver
#jdbc.url=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
#jdbc.user=root
#jdbc.password=123456

#druid数据源配置,mysql 5和mysql 8配置信息不同
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud?serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=123456

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>


    
        
        
    

    
        
    

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>


    
    

    
    
        
        
        
        
    

    
    
        
        
    

    
    
    
    
    

5. 创建数据库

  • 一个库ssm_crud,两个表tbl_depttbl_emp
-- ----------------------------
-- 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) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`dept_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- 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) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `d_id` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`emp_id`) USING BTREE,
  INDEX `fk_emp_dept`(`d_id`) USING BTREE,
  CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1036 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

6. MyBatis Generator逆向工程

逆向生成

  • 根据现有的数据库结构生成对象的JavaBean、Dao接口、Mapper.xml等

  • 在ssm_crud根目录下创建mbg.xml配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    
    
    
        
    
            
            
    
            
            
                
                
                
            
    
            
            
    
            
            
                
            
    
            
            
    
            
            
    
            
            
    
            
            
  • com.ssm.test包中任意创建一个测试方法,然后运行

    /**
     * MyBatis Generator逆向工程
     */
    public class MBGTest {
        public static void main(String[] args) throws InvalidConfigurationException, IOException, XMLParserException, SQLException, InterruptedException {
            List warnings = new ArrayList();
            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);
        }
    
    }
    
  • 之后项目自动生成文件,主要分三部分

    • 每个表生成对应JavaBean和对应的查询条件Example
    • Dao接口
    • Mapper.xml文件

联表查询

  • 自动生成的功能不能满足指定的查询条件,所以需要修改

  • 实现一条sql完成联表查询,在逆向工程的基础上,需要修改以下地方

  • JavaBean

    • Department

      package com.ssm.bean;
      
      public class Department {
          private Integer deptId;
      
          private String deptName;
      
          //如果用了构造器,一定要写无参构造器
          public Department() {
              super();
          }
          public Department(Integer deptId, String deptName) {
              super();
              this.deptId = deptId;
              this.deptName = deptName;
          }
      
          //get/set/toString
      }
      
    • Employee

      package com.ssm.bean;
      
      public class Employee {
          private Integer empId;
      
          private String empName;
      
          private String gender;
      
          private String email;
      
          private Integer dId;
      
          // 增加联合查询
          private Department department;
          // 如果用了构造器,一定要写无参构造器
          public Employee() {
              super();
          }
          // 不加Department的属性
          public Employee(Integer empId, String empName, String gender, String email, Integer dId) {
              super();
              this.empId = empId;
              this.empName = empName;
              this.gender = gender;
              this.email = email;
              this.dId = dId;
          }
      
          // get/set/toString
      }
      
  • Dao

    • EmployeeMapper

      public interface EmployeeMapper {
      	//...
      	
      	//新增两个查询方法,用于联合查询
          List selectByExampleWithDept(EmployeeExample example);
          Employee selectByPrimaryKeyWithDept(Integer empId);
      }
      
  • Mapper

    • EmployeeMapper.xml

      
      	
      	
          
          
          
      
          
          
        	e.emp_id, e.emp_name, e.gender, e.email, e.d_id, d.dept_id, d.dept_name
          
          
          
              
              
              
              
              
              
              
                  
                  
              
          
      
          
          
          
          
          
      	
      
      

批量插入

  • com.ssm.test中任意创建测试类,测试sql连接并添加数据

    //如果您想在测试中使用Spring测试框架功能(例如)@MockBean,则必须使用@ExtendWith(SpringExtension.class)。它取代了不推荐使用的JUnit4@RunWith(SpringJUnit4ClassRunner.class)
    @ExtendWith(SpringExtension.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class MapperTest {
    
    	@Autowired
    	DepartmentMapper departmentMapper;
    	@Autowired
    	EmployeeMapper employeeMapper;
    	//批量sqlSession
    	@Autowired
    	SqlSessionTemplate sqlSessionTemplate;
    
        @Test
        public void test(){
            //Employee employee = employeeMapper.selectByPrimaryKeyWithDept(1);
            //System.out.println(employee);
            
            //1.插入部门
    //		departmentMapper.insertSelective(new Department(null, "开发部"));
    //		departmentMapper.insertSelective(new Department(null, "测试部"));
    		
    		//2.插入员工
    //		employeeMapper.insertSelective(new Employee(null, "Tom", "M", "Tom@123.com", 1));
    		
    		//3.批量插入
    		//使用sqlSessionTemplat可以实现批量,不使用就不是
    		EmployeeMapper eMapperTemplat = sqlSessionTemplate.getMapper(EmployeeMapper.class);
    		for(int i = 0 ; i <= 1000 ; i++) {
    			
    			String uuid = UUID.randomUUID().toString().substring(0, 5) + i;
    			//这里继续使用employeeMapper就不行
    			//employeeMapper.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
    			
    			//使用employeeMapperTemplat批量插入
    			eMapperTemplat.insertSelective(new Employee(null, uuid, "M", uuid+"@123.com", 1));
    		}
    	}
        
    }
    

7. 总结

到目前为止,Spring、SpringMVC、MyBatis都已经配置完成,各功能可以连通,可以进行编写增删改查的代码了。目前目录结构如下

ssm_crud
    src
        main
        	java
        		com.ssm.bean
        			Department.java
        			EmployeeExample.java
        			Employee.java
        			DepartmentExample.java
        		com.ssm.dao
        			EmployeeMapper.java
        			DepartmentMapper.java
        		com.ssm.service
        		com.ssm.controller
        		com.ssm.test
        			MapperTest.java
        			MBGTest.java
        		com.ssm.utils
        	resources
        		mapper
        			DepartmentMapper.xml
        			EmployeeMapper.xml
        		applicationContext.xml
        		dbconfig.properties
        		mybatis-config.xml
        		springmvc.xml
            webapp
            	static
            		bootstrap-3.3.7-dist
        			jquery-1.12.4.js
                WEB-INF
                	views
                	web.xml
                index.jsp
	pom.xml
	mbg.xml
SSM