Sprig框架集成(SSM框架) | Sping+SpringMVC+Mybatis

Posted wei_shuo

tags:

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

SSM框架

SSM是sping+springMVC+mybatis集成的框架:标准的MVC模式,整个系统划分为表现层,controller层,service层,DAO层四层

  • 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整合

Mybatis层

配置

  • 数据库环境配置
CREATE DATABASE `SSMBuild`;

USE `SSMBuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books`
(
    `bookID`     INT(10)      NOT NULL AUTO_INCREMENT COMMENT '书id',
    `bookName`   VARCHAR(100) NOT NULL COMMENT '书名',
    `bookCounts` INT(11)      NOT NULL COMMENT '数量',
    `detail`     VARCHAR(200) NOT NULL COMMENT '描述',
    KEY `bookID` (`bookID`)
) ENGINE = INNODB
  DEFAULT CHARSET = utf8;

INSERT INTO `books`(`bookID`, `bookName`, `bookCounts`, `detail`)
VALUES (1, 'Java', 1, '从入门到放弃'),
       (2, 'mysql', 10, '从删库到跑路'),
       (3, 'Linux', 5, '从进门到进牢');
  • 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>org.example</groupId>
    <artifactId>SSMBuild</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--依赖导入-->
    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</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.2</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.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

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

        <!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</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>
</project>

resources包

  • mybatis-config.xml(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操作-->

    <!--typeAliases:它仅用于XML配置,意在降低冗余的全限定类名书写-->
    <typeAliases>
        <package name="com.wei.pojo"/>
    </typeAliases>

    <!-- 使用映射器接口实现类的完全限定类名 -->
    <mappers>
        <mapper class="com.wei.dao.BookMapper"/>
    </mappers>
</configuration>
  • applicationContext.xml(spring核心配置文件)
<?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>
  • database.properties(核心配置文件)
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用MYSQL8.0+,需要增加时区配置;&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

java包

  • com.wei.pojo.Books(数据库对应的实体类 )
package com.wei.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 detail;


  • com.wei.dao.BookMapper(编写Dao层的 Mapper接口)
package com.wei.dao;

import com.wei.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper 

    //增加一本书
    int addBook(Books books);

    //删除一本书,@Param注解给参数命名
    int deleteBookById(@Param("bookId") int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(@Param("bookId") int id);

    //查询全部书
    List<Books> queryAllBook();

  • com.wei.pojo.BooksMapper.xml(编写接口对应的 Mapper.xml 映射文件,导入MyBatis的包)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wei.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#bookName,#bookCounts,#detail);
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID=#bookId
    </delete>
    
    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName=#bookName,bookCounts=#bookCounts,detail=#detail
        where bookID=#bookID;
    </update>

    <select id="queryBookById" parameterType="int" resultType="Books">
        select * from ssmbuild.books where bookID=#bookID;
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books;
    </select>
</mapper>
  • 编写Service层的接口
package com.wei.service;

import com.wei.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService 

    //增加一本书
    int addBook(Books books);

    //删除一本书,@Param注解给参数命名
    int deleteBookById(int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(int id);

    //查询全部书
    List<Books> queryAllBook();


  • 编写Service层的实现类
package com.wei.service;

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

import java.util.List;

public class BookServiceImpl implements BookService

     //调用dao层的操作,设置一个set接口,方便Spring管理
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) 
        this.bookMapper = bookMapper;
    

    @Override
    public int addBook(Books books) 
        return bookMapper.addBook(books);
    

    @Override
    public int deleteBookById(int id) 
        return bookMapper.deleteBookById(id);
    

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

    @Override
    public Books queryBookById(int id) 
        return bookMapper.queryBookById(id);
    

    @Override
    public List<Books> queryAllBook() 
        return bookMapper.queryAllBook();
    

Spring层

resource包

  • spring-dao.xml(spring整合dao层)
<?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">

    <!--关联数据库配置文件:Spring读取数据库配置文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--连接池:
    dbcp:半自动化操作,不能自动连接
    c3p0:自动化操作,自动化的加载配置文件,并且可以自动设置到对象中
    druid、hikari-->

    <!--
    dbcp:
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    -->

    <!--c3p0-->
    <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以上是关于Sprig框架集成(SSM框架) | Sping+SpringMVC+Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

ssm整合-Sping整合Mybatis框架06

ssm整合-Sping整合Mybatis框架06

ssm整合-Sping整合Mybatis框架配置事务07

ssm整合-Sping整合Mybatis框架配置事务07

(第02节)集成Sping框架

Elasticsearch与Sping Data框架的集成