后端SSM(Spring + SpringMVC + Mybatis)框架整合

Posted 双份浓缩馥芮白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了后端SSM(Spring + SpringMVC + Mybatis)框架整合相关的知识,希望对你有一定的参考价值。

✨SSM简介

SSM(Spring+SpringMVC+MyBatis)框架集由SpringMyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。

常作为数据源较简单的web项目的框架。

Spring

Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。

SpringMVC

SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。

Mybatis

mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。

SSM整合

页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据。


本Blog按照【狂神说Java】SSM框架最新整合教学IDEA版_哔哩哔哩_bilibili 进行SSM整合(对应视频 P1-P4部分)

后续更新相关功能实现(对应视频 P5-P7 部分)


✨数据库

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
`book_id` INT(10) NOT NULL AUTO_INCREMENT COMMENT \'书id\',
`book_name` VARCHAR(100) NOT NULL COMMENT \'书名\',
`book_counts` INT(11) NOT NULL COMMENT \'数量\',
`book_detail` VARCHAR(200) NOT NULL COMMENT \'描述\',
KEY `book_id` (`book_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`book_id`,`book_name`,`book_counts`,`book_detail`)VALUES
(1,\'《Java核心技术》\',1,\'Java入门\'),
(2,\'《Effective Java》\',10,\'Java进阶\'),
(3,\'《深入理解Java虚拟机》\',10,\'JVM\'),
(4,\'《A Byte of Python》\',10,\'Python入门\'),
(5,\'《大话设计模式》\',10,\'设计模式\');

✨Maven

依赖

<!--    依赖: junit 数据库驱动 连接池 servlet jsp mybatis mybatis-spring spring-->
    <dependencies>
<!--        Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
<!--        数据库驱动-->
        <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.49</version>
        </dependency>
<!--        数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>

<!--        Servlet JSP-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

<!--        Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

<!--        Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</version>
        </dependency>

<!--        Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>

静态资源导出

<!--    静态资源导出-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

✨项目结构(初始化)

新建软件包与XML

  • com.example.pojo

  • com.example.dao

  • com.example.service

  • com.example.controller

  • 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>
    
    </configuration>
    
  • applicationContext.xml

    <?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">
    
    </beans>
    

✨Mybatis

database.properties

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password = root

Mybatis核心配置文件

<?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>

<!--    配置数据源 -> Spring-->

<!--    驼峰命名自动映射-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <package name="com.example.pojo"/>
    </typeAliases>

</configuration>

实体类

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookId;
    private String bookName;
    private int bookCounts;
    private String bookDetail;
}

Mapper接口

package com.example.dao;

import com.example.pojo.Books;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface BookMapper {
    int insertBook(Books books);

    int deleteBookById(@Param("bookId") int bookId);

    int updateBook(Books books);

    Books getBookById(@Param("bookId") int bookId);

    @Select("select * from ssmbuild.books")
    List<Books> listBooks();
}

Mapper.xml

<?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.example.dao.BookMapper">
    <insert id="insertBook" parameterType="books">
        insert into ssmbuild.books(book_id, book_name, book_counts, book_detail)
        VALUES (#{bookId}, #{bookName}, #{bookCounts}, #{bookDetail})
    </insert>
    
    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where book_id = #{bookId}
    </delete>

    <update id="updateBook" parameterType="books">
        update ssmbuild.books
        set book_name = #{bookName}, book_counts = #{bookCounts}, book_detail = #{bookDetail}
        where book_id = #{bookId}
    </update>
    
    <select id="getBookById" resultType="books">
        select * from ssmbuild.books where book_id = #{bookId}
    </select>

</mapper>

Service层

接口

package com.example.service;

import com.example.pojo.Books;

import java.util.List;

public interface BookService {
    int insertBook(Books books);

    int deleteBookById(int bookId);

    int updateBook(Books books);

    Books getBookById(int bookId);

    List<Books> listBooks();
}

实现类

package com.example.service;

import com.example.dao.BookMapper;
import com.example.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService{

//    service层调dao层

    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public int insertBook(Books books) {
        return bookMapper.insertBook(books);
    }

    @Override
    public int deleteBookById(int bookId) {
        return bookMapper.deleteBookById(bookId);
    }

    @Override
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    @Override
    public Books getBookById(int bookId) {
        return bookMapper.getBookById(bookId);
    }

    @Override
    public List<Books> listBooks() {
        return bookMapper.listBooks();
    }
}

✨Spring

resources 下新建

  • spring-dao.xml

  • spring-service.xml


Spring整合Mybatis

spring-dao.xml

<?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
       https://www.springframework.org/schema/context/spring-context.xsd">
    
<!--    配置整合Mybatis-->

<!--    1. 关联数据库文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

<!--    2. 数据库连接池 -->
    <!--数据库连接池
        dbcp 半自动化操作 不能自动连接
        c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
        druid hikari
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

<!--    3. 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

<!--    4. 配置扫描Dao接口包,动态实现Dao接口注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.example.dao"/>
    </bean>

</beans>

Spring整合service层

spring-service.xml

<?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相关的bean -->
    <context:component-scan base-package="com.example.service" />

<!--    BookServiceImpl注入到IOC容器中(可以使用配置或注解实现)-->
    <bean id="bookServiceImpl" class="com.example.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

<!--     配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

<!--    AOP事务支持...-->

</beans>

✨SpringMVC

resources 下新建 spring-mvc.xml


添加Web框架支持

在项目根目录右键 -> 添加框架支持

**并在 WEB-INF 下新建目录 jsp **

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         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">

<!--    DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--注意:加载的是总的配置文件-->
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!--    encodingFilter 乱码过滤-->
    <filter>
        <filter-name>encodingFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

spring-mvc.xml

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

<!--    配置SpringMVC -->

<!--    1. 开启SpringMVC注解驱动-->
    <mvc:annotation-driven/>
<!--    2. 静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>

<!--    3. 配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    4. 扫描web相关的bean -->
    <context:component-scan base-package="com.example.controller"/>

</beans>

✨配置文件整合

applicationContext.xml 中导入各层配置文件

<?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">

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
    
</beans>

✨项目结构(SSM整合)


✨参考及引用

SSM(SSM 框架集)_百度百科 (baidu.com)

【狂神说Java】SSM框架最新整合教学IDEA版_哔哩哔哩_bilibili

狂神说SpringMVC05:整合SSM框架 (qq.com)


⭐转载请注明出处

本文作者:双份浓缩馥芮白

原文链接:https://www.cnblogs.com/Flat-White/p/15200766.html

版权所有,如需转载请注明出处。

以上是关于后端SSM(Spring + SpringMVC + Mybatis)框架整合的主要内容,如果未能解决你的问题,请参考以下文章

day01-项目介绍+SSM环境搭建

SSM(Spring + Springmvc + Mybatis)框架面试题

转SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

springmvc和ssh,ssm的区别

shiro整合SSM(spring_springmvc_mybatis)

SSM(SpringMVC+Spring+Mybatis)