Spring+SpringMVC+MyBatis三大框架整合

Scroll Down

1. 依赖项

<?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>SSM</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>images</module>
    </modules>

    <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.47</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>javax.servlet-api</artifactId>
            <version>4.0.0</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.6</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.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

    </dependencies>
</project>

2. 包过滤

在pom.xml添加以下代码

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

3. 创建必要目录和文件

4. 修改配置文件

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"
       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
">
    <context:property-placeholder location="classpath:database.properties"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

database.properties 配置数据库信息

jdbc.driver=com.mysql.jdbc.Driver
# Mysql8.0+增加时区配置serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/java_study?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

spring-dao.xml 配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 定义数据源 -->
    <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.username}"/>

        <property name="maxPoolSize" value="10"/>
        <property name="minPoolSize" value="2"/>

        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="10000"/>
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 注入SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    
    <!-- 扫描dao层下的所有包 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.buaoy.dao"/>
    </bean>

</beans>

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>

    <!-- 方便取别名 -->
    <typeAliases>
        <package name="com.buaoy.pojo"/>
    </typeAliases>

    <!-- 寻找所有mapper -->
    <mappers>
        <package name="com.buaoy.dao"/>
    </mappers>
</configuration>

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

    <context:component-scan base-package="com.buaoy.service"/>

    <bean class="com.buaoy.service.ImageServiceImpl" id="imageServiceImpl">
        <property name="imageMapper" ref="imageMapper"/>
    </bean>

    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <context:component-scan base-package="com.buaoy.controller"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <mvc:resources mapping="/static/images/**" location="/static/images/" />
</beans>

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">
    <servlet>
        <servlet-name>springmvc</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>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <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>
</web-app>

5. dao层

ImageMapper接口

package com.buaoy.dao;

import com.buaoy.pojo.Image;

import java.util.List;

public interface ImageMapper {
    // 增加一张图片
    int insert(Image image);
    // 通过id删除图片
    int deleteById(int id);
    // 通过id更新图片
    int updateById(Image image);
    // 通过id查询图片
    Image selectById(int id);
    // 查询所以图片
    List<Image> selectAll();
}

ImageMapper.xml

<?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.buaoy.dao.ImageMapper">
    <insert id="insert" parameterType="Image">
        INSERT java_study.images (location, title)
        VALUES (#{location}, #{title});
    </insert>

    <select id="delete" parameterType="int">
        DELETE FROM java_study.images
        WHERE id=#{id};
    </select>

    <update id="updateById" parameterType="Image">
        UPDATE java_study.images
        SET id=#{id}, location=#{location}, title=#{title}
        WHERE id=#{id};
    </update>

    <select id="selectAll" resultType="Image">
        SELECT * FROM java_study.images;
    </select>

    <select id="selectById">
        SELECT * FROM java_study.images
        WHERE id=#{id};
    </select>
</mapper>

6. service层

service层调用dao层

定义接口

package com.buaoy.service;

import com.buaoy.pojo.Image;

import java.util.List;

public interface ImageService {
    int insert(Image image);
    int deleteById(int id);
    int updateById(Image image);
    Image selectById(int id);
    List<Image> selectAll();
}

实现接口,同时可以实现AOP

package com.buaoy.service;

import com.buaoy.dao.ImageMapper;
import com.buaoy.pojo.Image;

import java.util.List;

public class ImageServiceImpl implements ImageService{
    // 业务层调dao层
    private ImageMapper imageMapper;

    public void setImageMapper(ImageMapper imageMapper) {
        this.imageMapper = imageMapper;
    }

    @Override
    public int insert(Image image) {
        return imageMapper.insert(image);
    }

    @Override
    public int deleteById(int id) {
        return imageMapper.deleteById(id);
    }

    @Override
    public int updateById(Image image) {
        return imageMapper.updateById(image);
    }

    @Override
    public Image selectById(int id) {
        return imageMapper.selectById(id);
    }

    @Override
    public List<Image> selectAll() {
        return imageMapper.selectAll();
    }
}

7. 视图层

package com.buaoy.controller;

import com.buaoy.pojo.Image;
import com.buaoy.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/images")
public class ImagesController {

    @Autowired
    @Qualifier("imageServiceImpl")
    private ImageService imageService;

    @RequestMapping("/list")
    public String list(Model model){
        List<Image> imageList=imageService.selectAll();
        model.addAttribute("list", imageList);
        System.out.println(imageList);
        return "list";
    }
}