快速从零开始整合SSM,小白包会(1)


       整合SSM,关键就是几个xml的配置.

准备:

  1.   Idea(配置好tomcat,可以安装插件freeMybatis,提高效率,安装插件不难,百度经验就有)

  2.   下载好数据库MySql,以及可视化管理软件

  3.   一双手,宝贵的半个小时

  4.   对SSM,有认识,后面我会继续写有关这三个框架的内容.

开始:

  首先,明确我们这里的工作:

    建立一个通用的SSM项目,或者知道快速建立它的方法,以便于后面有什么项目,分析完可以直接就上手,避免在初始化项目,整合框架时耗费时间.

        工作目标:

    待会如果我们将存储在数据库里面表的信息在控制台打印出来了,那么Spring与MyBatis整合成功,如果在前端页面显示了数据库的数据,那么可以说三个框架整合成功.

   

  提示:成功一次之后,可以反反复复多建几次,到达熟练,也可以保存模板,后面直接用.我就是从零开始边建项目边写这个博客,我都完成了,你照着来应该不会错.

    毒鸡汤:在这个过程中,可能会遇到很多麻烦,但大部分都可以百度解决,也有可能被误导,但不管怎么样结果是一定成功的,毕竟它具有可预测性和有限性,而只要成功一次就可以保证成功无数次.

   我还是个小白,第一次写博客(马上要期末考试了,哈哈),希望以这种方式来记录一下自己踩过的坑,都是自己慢慢摸出来的,不科学也不规范,我也希望大佬们可以多多指导.

  第一步,在Idea上面新建一个项目:

 此时项目应该是白的,这个样子:

我们下面建几个包和配置文件:

 在config下面建立这些配置文件(这其实就是核心的配置,文件内容先不管,后面直接复制):

下面导入jar包,可以选择自动下载,或者直接使用Maven项目来添加,这里我们手动添加:

 

 把自己的准备Jar包统统导进来即可.

 

再做一点小手脚,标识一下文件(test包是刚刚建的,就是一个普通的包,所以没有截图):

项目就是这个样子了:

  至此, 第一步初始化项目完成,已经完成70%了.

  第二步:使项目可以跑起来,在前端页面可以看到数据库的存储的信息.

     1. 配置tomcat,把刚刚的建的配置文件加上内容.

     2. 在数据库里面新加一表,插入一条测试数据,并为该表建立mapper文件,和接口(可以使用插件完成).

     3.简单的编写一下,开始测试.

 1.配置Tomcat,比较简单,就不步步展示了.后面放假了可以详细的写一下.

 2.各个配置文件的内容:

  applicationContext.xml :

 1 <?xml version="1.0" encoding="UTF-8"?>
 2  3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:tx="http://www.springframework.org/schema/tx"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        https://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx.xsd">
12     
13     
14     package="service"/>
15     class="org.apache.commons.dbcp.BasicDataSource">
16         
17         
18         
19         
20         
21         
22     
23     
24     
25     class="org.mybatis.spring.mapper.MapperScannerConfigurer">
26         
27     
28     class="org.mybatis.spring.SqlSessionFactoryBean">
29         
30         
31     
32     
33     
34     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
35         
36     
37     
38    
39 

  db.properties(要根据自己的数据库更改) :

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3308/exam?useUnicode=true&characterEncoding=utf8&useSSL=false
3 jdbc.username=root
4 jdbc.password=123456
5 jdbc.maxTotal=30
6 jdbc.maxIdle=10
7 jdbc.initialSize=5

  log4j.properties :

1 # Global logging configuration
2 log4j.rootLogger=ERROR, stdout
3 # MyBatis logging configuration...
4 log4j.logger.org.mybatis.example.BlogMapper=DEBUG
5 # Console output...
6 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
7 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
8 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  mybatis-config.xml :

1 <?xml version="1.0" encoding="UTF-8"?>
2 DOCTYPE configuration
3         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
5 
6     
7         <package name="po"/>
8     
9 

  springmvc-config.xml :

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

       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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    package="controller"/>
    

    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        
    

   web.xml

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

         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">
    
    
        contextConfigLocation
        classpath:config/applicationContext.xml
    
    
        class>org.springframework.web.context.ContextLoaderListenerclass>
    
    
    
    
        encoding
        class>org.springframework.web.filter.CharacterEncodingFilterclass>
        
            encoding
            UTF-8
        
    
    
        encoding
        *.action
    
    
    
    
        springmvc
        class>org.springframework.web.servlet.DispatcherServletclass>
        
            contextConfigLocation
            classpath:config/springmvc-config.xml
        
        1
    
    
        springmvc
        /
    
    

   3.在数据库里面建表,插入一条数据.

 4.使用插件生成这个测试表的mapper文件和dao接口

  最后生成的项目结构:

  生成具体的代码(这都是插件自动生成的,省事):

  UserDao接口 :

package mapper;

import org.springframework.transaction.annotation.Transactional;
import po.User;

@Transactional
public interface UserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

  UserDao.xml :

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


  
    
    
    
    
    
    
    
    
  
  
    user.id as user_id, user.userName as user_userName, user.`passWord` as `user_passWord`, 
    user.phone as user_phone, user.realName as user_realName, user.sex as user_sex, user.address as user_address, 
    user.email as user_email
  
  
  
    delete from user
    where id = #{id,jdbcType=INTEGER}
  
  
    insert into user (userName, `passWord`, phone, 
      realName, sex, address, 
      email)
    values (#{userName,jdbcType=VARCHAR}, #{passWord,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, 
      #{realName,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, 
      #{email,jdbcType=VARCHAR})
  
  
    insert into user
    
      <if test="userName != null">
        userName,
      if>
      <if test="passWord != null">
        `passWord`,
      if>
      <if test="phone != null">
        phone,
      if>
      <if test="realName != null">
        realName,
      if>
      <if test="sex != null">
        sex,
      if>
      <if test="address != null">
        address,
      if>
      <if test="email != null">
        email,
      if>
    
    
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      if>
      <if test="passWord != null">
        #{passWord,jdbcType=VARCHAR},
      if>
      <if test="phone != null">
        #{phone,jdbcType=VARCHAR},
      if>
      <if test="realName != null">
        #{realName,jdbcType=VARCHAR},
      if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      if>
    
  
  
    update user
    
      <if test="userName != null">
        userName = #{userName,jdbcType=VARCHAR},
      if>
      <if test="passWord != null">
        `passWord` = #{passWord,jdbcType=VARCHAR},
      if>
      <if test="phone != null">
        phone = #{phone,jdbcType=VARCHAR},
      if>
      <if test="realName != null">
        realName = #{realName,jdbcType=VARCHAR},
      if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      if>
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update user
    set userName = #{userName,jdbcType=VARCHAR},
      `passWord` = #{passWord,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      realName = #{realName,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  

  User类 : 

package po;

import java.io.Serializable;


/**
 * user
 * @author 
 */

public class User implements Serializable {
    /**
     * id,主键
     */
    private Integer id;

    /**
     * 账户
     */
    private String userName;

    /**
     * 密码
     */
    private String passWord;

    /**
     * 手机号码
     */
    private String phone;

    /**
     * 真实姓名
     */
    private String realName;

    /**
     * 性别
     */
    private String sex;

    /**
     * 地址(收货)
     */
    private String address;

    /**
     * 电子邮件
     */
    private String email;

    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName()))
            && (this.getPassWord() == null ? other.getPassWord() == null : this.getPassWord().equals(other.getPassWord()))
            && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
            && (this.getRealName() == null ? other.getRealName() == null : this.getRealName().equals(other.getRealName()))
            && (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex()))
            && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))
            && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail()));
    }

    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 getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode());
        result = prime * result + ((getPassWord() == null) ? 0 : getPassWord().hashCode());
        result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
        result = prime * result + ((getRealName() == null) ? 0 : getRealName().hashCode());
        result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode());
        result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());
        result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", userName=").append(userName);
        sb.append(", passWord=").append(passWord);
        sb.append(", phone=").append(phone);
        sb.append(", realName=").append(realName);
        sb.append(", sex=").append(sex);
        sb.append(", address=").append(address);
        sb.append(", email=").append(email);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

 5.测试Spring与Mybatis的基本整合

  1.在test包下面建一个Test类,用来测试 :

  其内容分别为:

  Test类 :

import mapper.UserDao;
import org.springframework.context.ApplicationContext;
import util.SpringUtil;

/**
 * test
 *
 * @author Mr.green
 * @date 2021/11/21 17:27
 */
public class Test {

    @org.junit.jupiter.api.Test
    void test(){
        ApplicationContext applicationContext= SpringUtil.getApplicationContext();
        System.out.println(applicationContext.getBean(UserDao.class).selectByPrimaryKey(1));
    }
}

  SpringUtil类:

 1 package util;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 /**
 7  * Spring
 8  *
 9  * @author Mr.green
10  * @date 2021/11/21 17:28
11  */
12 public class SpringUtil {
13     /*获取spring上下文解析器*/
14    static public ApplicationContext getApplicationContext(){
15         return  new ClassPathXmlApplicationContext("config/applicationContext.xml");
16     }
17 
18 
19 }

直接开始测试 :

Nice,Spring与Mybatis整合成功.

6.测试Sping,Mybatis,SpringMvc的整合

  1.建一个jsp页面,用来显示数据库的数据

  2.建一个controller响应处理前端的请求

1:  建一个jsp页面

    a.jsp的内容:

<%--
  Created by IntelliJ IDEA.
  User: Philosohy
  Date: 2021/11/22
  Time: 13:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    ${user.id}
${user.userName}
${user.passWord}

2 .建一个controller:

   其内容:

package controller;

import util.SpringUtil;
import mapper.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * test
 *
 * @author Mr.green
 * @date 2021/11/21 18:23
 */
@Controller
public class TestController {

    @RequestMapping("/test")
    public String test(Integer id, Model model){
        ApplicationContext applicationContext= SpringUtil.getApplicationContext();
        model.addAttribute("user",applicationContext.getBean(UserDao.class).selectByPrimaryKey(1));

        return "a";
    }
}

 3.开始测试,启动项目,在跳出来的网页后面加上test :

这不就飞起了!!!!