步骤超详细的spring+springMVC+Mybatis整合

SSM整合

目录

1.项目概述
2.创建项目
3.搭建环境,引入相关配置
4.springMVC的环境搭建及测试
5.Mybatis的环境搭建及测试
6.spring的环境搭建及测试
7.SSM的整合
8.添加增删改方法,进一步完善项目
9.项目完整源码

1.SSM概述

该项目整合了spring、springMVC和Mybatis,比较简单易懂,对刚学完的同学来说还是有一些收获。

springMVC:应用于web层,相当于controller,用来处理用户请求,方便前后端传输数据

spring:ioc容器装载bean,不用每次初始化new对象,以及aop和事务管理等,在很大程度上帮助我们提升开发效率。

Mybatis:mybatis让开发者将主要精力放在sql上,通过mybatis提供的映射方式可以很灵活的写出满足需要sql语句,换句话说,mybatis可以将向preparedStatement中的输入参数自动进行输入映射,将查询结果集灵活映射成java对象


2.创建项目

点击create new project
在这里插入图片描述

选择maven工程,用maven管理jar包很方便,不用maven的话,需要自己一个个找jar包。
勾选创建骨架,选择webapp,如图,不要选错了,然后点击next
在这里插入图片描述
这里可以随意填
在这里插入图片描述
为了使得项目快速创建,点击右边加号,name填archetypeCatalog,value填internal,填完点next
在这里插入图片描述
然后点finish,等项目创建成功。


3.搭建环境,引入相关配置

3.1.数据库相关

创建ssm数据库,在此数据库内创建名为movie_list的表,并设置相关属性

create database ssm;
use ssm;
create table movie_list(
id int primary key auto_increment,
name varchar(20),
director varchar(20),
actor varchar(20)
)

在表中插入几条记录,并查看是否执行成功

insert  into movie_list(`name`,`director`,`actor`) values('燃烧','李沧东','刘亚仁');
insert  into movie_list(`name`,`director`,`actor`) values('东邪西毒','王家卫','张国荣');
insert  into movie_list(`name`,`director`,`actor`) values('重庆森林','王家卫','梁朝伟');
insert  into movie_list(`name`,`director`,`actor`) values('海街日记','是枝裕和','绫濑遥');
insert  into movie_list(`name`,`director`,`actor`) values('低俗小说','昆汀','乌玛瑟曼');
insert  into movie_list(`name`,`director`,`actor`) values('星际穿越','诺兰','马修麦康纳');
select * from movie_list;

查询结果
在这里插入图片描述

3.2 环境搭建

在ssm.pom文件中导入相关的坐标

<?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>cn.txl</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>8.0.16</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>


<!--    单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

<!--    数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- 日志 log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
<!--    log end-->

    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

<!--    数据库连接池-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

在main目录下新建两个包,一个名为java,用于存放.java文件,另一个叫resources,存放配置文件
在这里插入图片描述
在java目录下建两级包,包名可以随意,然后建controller、service、dao、domain、test五个包,分别用于管理表现层,业务层、持久层,javabean和测试类,结构目录如下:
在这里插入图片描述
在domain包下创建一个名为Movies的类,并生成相应的set、get和tostring方法,并实现序列化接口

import java.io.Serializable;

public class Movies implements Serializable {
    private Integer id;
    private String name;
    private String director;
    private String actor;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }

    @Override
    public String toString() {
        return "Movies{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", director='" + director + '\'' +
                ", actor='" + actor + '\'' +
                '}';
    }
}

配置tomcat

如图:
在这里插入图片描述

在这里插入图片描述

名称改为ssm,其他配置改为自己习惯的
在这里插入图片描述
在这里插入图片描述
然后选择第一个点击ok


4.springMVC的环境搭建及测试

在整合之前,需要分别对三个框架独立测试是否能成功,能够独立运行,说明搭建成功,然后再整合,首先搭建测试springMVC

在WEB-INF下创建pages目录,然后在pages下创建success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>congratulations!</h1>


</body>
</html>

在resources下创建springmvc.xml的配置文件,并导入相关约束,之后开启扫描,配置视图解析器,配置静态资源,开启springMVC对注解的支持

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       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
        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">
<!--    以上为导入的相关约束-->

<!--    扫描controller包-->
    <context:component-scan base-package="cn.txl.controller"/>

<!--    配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--        prefix表示前缀,路径名-->
        <property name="prefix" value="/WEB-INF/pages/"/>
<!--        suffix表示后缀,文件的后缀名-->
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    配置使得静态资源不被过滤-->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>


<!--    开启springMVC对注解的支持-->
    <mvc:annotation-driven/>
</beans>

注意:此时若发现静态资源配置的location爆红是正常的,因为此时还没有创建静态资源的相关目录,但是也不影响程序的运行,但是此配置很重要,在正常开发时,如果不配置,那么所有的静态资源都会被拦截器拦截,导致静态资源无法正常加载,页面出现错误

在web.xml文件中配置前端控制器以及解决中文乱码问题

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

<!--  配置前端控制器-->
  <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:springmvc.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>

<!--  解决中文乱码问题-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

注意:此时若发现web-app处爆红是正常的,不影响程序正常运行


在controller包下新建MoviesController.java类,并添加查询所有方法,这里需要先测试是否能正常执行,所以先打印一句话,稍后再补充正确的逻辑代码

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.Serializable;
import java.util.List;

@Controller
@RequestMapping("moviesController")
public class MoviesController {

    @RequestMapping("findAll")
    public String findAll(){

        System.out.println("controller的findAll方法");
        return "success";
    }

}

@Controller注解用于标记一个类,使用它标注的类就是一个springMVC Controller对象,分发处理器就会扫描使用该对象的方法
@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径

由于idea帮我们创建的index.jsp没有相关约束信息,这里为了方便,先把index.jsp删除,再创建一个,就有相关约束信息了,当然也可以不这么做,自己写
添加一个超链接如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="moviesController/findAll">findAll方法</a>

</body>
</html>

此时运行项目,如下:
在这里插入图片描述
点击超链接,如下
在这里插入图片描述

控制台:
在这里插入图片描述
可以看到在浏览器点击超链接之后,就转到了success.jsp页面,控制台也输出了findAll方法打印的那句话,此时springMVC的环境搭建已经成功了

出错小结

若发现程序运行后,index页面没出来,显示404,如下:
在这里插入图片描述

  1. 可能是tomcat的配置有问题
  2. 也有可能是新建index.jsp文件时将名字写错
  3. 也可能是将index.jsp文件建到了其他包下,导致找不到资源,要将对应的文件放到对应的包下,这样便于管理,此时的项目目录结构如下:
    在这里插入图片描述

若能显示index.jsp界面,但是点击超链接后发生了404错误

  1. 超链接的href写错了,最前面没有/
    在这里插入图片描述
  2. 路径名称要和ControllerrequestMapping里面填写的一致,检查看看是不是哪里填错了
  3. tomcat配置与requestMapping填写不匹配出错
    如果配置tomcat时保留了最前面的/
    在这里插入图片描述
    那么requestMapping都不需要/
    在这里插入图片描述

如果tomcat配置最前面没有/

在这里插入图片描述
那么需要在类上的RequestMapping上加一个/
在这里插入图片描述


5.Mybatis的环境搭建及测试

在dao包下创建IMoviesDao接口,添加一个findAll方法,在方法上添加注解的sql语句

import cn.txl.domain.Movies;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface IMoviesDao {
    //查询所有电影
    
    @Select("select * from movie_list")
    public List<Movies> findAll();
}

在resources下新建MybatisConfig.xml文件和jdbc.properties,MybatisConfig.xml配置Mybatis,jdbc.properties写入数据库的四大属性,这样便于管理

<?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>
    <!--引入jdbc.properties文件-->
    <properties resource="jdbc.properties"></properties>
<!--    配置数据库-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
<!--                注入数据源-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>

            </dataSource>
        </environment>
    </environments>
    
<!--    开启要扫描的包-->
    <mappers>
        <package name="cn.txl.dao"/>
    </mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=

注意:不同的数据库版本,这里driver和url的配置是不一样的,由于我在ssm.pom文件里导入的是高版本的数据库,所以会和老版本的有所不同,根据自己的版本做相应的改动

在test包下新建TsetMybatis类,对Mybatis进行测试

import cn.txl.dao.IMoviesDao;
import cn.txl.domain.Movies;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {

    private InputStream in;
    SqlSessionFactory factory;
    private SqlSession sqlSession;
    private IMoviesDao dao;

    @Before
    public void init() throws IOException {
//        读取配置文件
        in= Resources.getResourceAsStream("MybatisConfig.xml");
//        获取工厂对象
        factory=new SqlSessionFactoryBuilder().build(in);
//        利用工厂获取sqlSession对象
        sqlSession=factory.openSession();
//        最后利用SqlSession对象获取dao对象
        dao=sqlSession.getMapper(IMoviesDao.class);
    }

    @After
    public void destroy() throws IOException {
        sqlSession.close();
        in.close();
    }

    @Test
    public void testFindAll(){
    //执行findAll方法,获取电影集合
        List<Movies> movies=dao.findAll();
        打印输出
        for(Movies movie:movies){
            System.out.println(movie);
        }
    }
}

测试查询所有的方法,由于这里没有dao接口的实现类,不能通过new的方式创建dao对象,那么就需要获取到dao代理对象,所以需要首先读取配置文件,
然后创建SqlSessionFactory 对象,利用这个对象创建工厂,然后利用工厂创建SqlSession对象,
最后通过通过SqlSession对象获得dao对象,也就是说做了这么多步,都是为了获取dao对象。
由于每次执行不同方法时都需要获取dao对象,所以这里将其抽取成一个方法,加上@Before注解这样每次执行方法前,都会先获取dao对象,destroy是每次执行完后,都需要释放相应的资源,所以加上@After,注意这两个注解是junit的不是Mybatis的。

执行结果
在这里插入图片描述
到这里已经可以和数据库交互了,Mybatis的环境搭建也成功了


6.spring的环境搭建及测试

在resources下新建一个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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    开启注解扫描,只希望spring处理service层和dao层,不处理controller层-->
    <context:component-scan base-package="cn.txl">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    
</beans>

在service包下创建IMoviesService接口,并添加一个findAll方法

import cn.txl.domain.Movies;

import java.util.List;

public interface IMoviesService {

    //查询所有电影
    public List<Movies> findAll();

}

在service下新建一个impl包,在impl里建一个IMoviesService 的实现类,名为MoviesServiceImpl,实现接口的方法,加上@Service注解

import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("moviesService")
public class MoviesServiceImpl implements IMoviesService {


    @Override
    public List<Movies> findAll() {
        System.out.println("MoviesServiceImpl的findAll方法执行了.............");
        return null;
    }
}

在test包下新建一个TestSpring类,测试spring环境搭建是否成功

import cn.txl.service.IMoviesService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {

    private IMoviesService service;

    @Test
    public void tsetFindAll(){
        ApplicationContext ac= new ClassPathXmlApplicationContext("applicationContext.xml");
        service=(IMoviesService)ac.getBean("moviesService");
        service.findAll();
    }
}

执行结果:
在这里插入图片描述
可以看到,方法已经成功执行了,此时各自的环境都已经搭建完成了,下面开始整合SSM


7.SSM的整合

7.1spring整合Mybatis

到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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    开启注解扫描,只希望spring处理service层和dao层,不处理controller层-->
    <context:component-scan base-package="cn.txl">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--    配置dao所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.txl.dao"></property>
    </bean>


        <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--    spring整合mybatis-->
    <!--    配置连接池-->
    <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}"/>

    </bean>

    <!--        配置SqlSession工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource"></property>
    </bean>



    <!--    配置spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>

    <!--    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--    配置aop增强 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.txl.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
</beans>

配置dao所在的包,配置SqlSession工厂需要注入数据源,所以要再配置一遍连接池,然后还需要配置事务管理器、事务通知和aop增强
由于在applicationContext.xml中做了spring和Mybatis的整合,MybatisConfig.xml里的配置在applicationContext.xml重复了一遍,此时可以直接将MybatisConfig.xml删除

做完这些配置后,获取dao对象就不需要再手动创建工厂等一系列繁琐的操作,只需要添加@Autowired注解,就可以自动注入,然后对MoviesServiceImpl 做如下更改,通过dao对象执行方法

import cn.txl.dao.IMoviesDao;
import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("moviesService")
public class MoviesServiceImpl implements IMoviesService {

    @Autowired
    private IMoviesDao dao;

    @Override
    public List<Movies> findAll() {
        System.out.println("MoviesServiceImpl的findAll方法执行了.............");
        return dao.findAll();
    }
}

对TestSpring 做如下更改,通过dao对象查询获取结果集,直接输出:

package cn.txl.test;


import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring {

    @Autowired
    private IMoviesService service;

    @Test
    public void tsetFindAll(){
        List<Movies> movies=service.findAll();
        for(Movies movie:movies){
            System.out.println(movie);
        }
    }
}

结果如下:
在这里插入图片描述
更改TestMybatis ,可以看到此时的代码变得很简洁

import cn.txl.dao.IMoviesDao;
import cn.txl.domain.Movies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestMybatis {
    
    @Autowired
    private IMoviesDao dao;


    @Test
    public void testFindAll(){
        List<Movies> movies=dao.findAll();
        for(Movies movie:movies){
            System.out.println(movie);
        }
    }
}

执行结果:
在这里插入图片描述
此时spring和Mybatis的整合就完成了,接下来整合spring和springMVC

7.2spring整合springMVC

修改MoviesController ,添加service对象,利用对象执行方法,并将查询结果存起来

import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.Serializable;
import java.util.List;

@Controller
@RequestMapping("/moviesController")
public class MoviesController {

    @Autowired
    private IMoviesService service;

    @RequestMapping("findAll")
    public String findAll(Model model){
        System.out.println("controller的findAll方法");
        List<Movies> movies=service.findAll();
        model.addAttribute("movies",movies);
        return "success";
    }

}

修改success.jsp,将isELIgnored设置为false,添加jstl核心库,遍历结果集输出,

<%--
  Created by IntelliJ IDEA.
  User: txllg
  Date: 2020/7/28
  Time: 14:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--添加jstl核心库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>congratulations!</h1>

<c:forEach items="${movies}" var="movie">
    ${movie.id}-
    ${movie.name}-
    ${movie.director}-
    ${movie.director}<br>

</c:forEach>

</body>
</html>


至此,还有很重要的一步就要成功了
在启动tomcat服务器时,由于controller层在web.xml配置过前端控制器,所以有关于springMVC的配置文件都会加载,但是service和dao层的配置文件不会加载,所以如果此时启动服务器运行程序,那必然是会失败的,失败结果如下:
在这里插入图片描述
因此还需要再web.xml中配置一个监听器,如下:

<!--  配置spring监听器,加载applicationContext.xml配置文件-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  <!--  配置文件路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

启动tomcat服务器,执行程序,如下:
在这里插入图片描述
点击超链接,结果如下:
在这里插入图片描述
控制台输出如下:
在这里插入图片描述

根据结果可以知道,当点击超链接时,dao对象查询了数据库,将结果集返回,并最后在success界面显示出来了,至此SSM的整合就基本完成了,还需要添加增删改的相关方法。

8.添加增删改方法,进一步完善项目

在IMoviesDao 中添加增删改查方法:

package cn.txl.dao;

import cn.txl.domain.Movies;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IMoviesDao {

    //查询所有电影
    @Select("select * from movie_list")
    public List<Movies> findAll();

    //根据id查询电影
    @Select("select * from movie_list where id=#{id}")
    public Movies findMovieById(Integer id);

    //增加电影
    @Insert("insert  into movie_list(`name`,`director`,`actor`) values(#{name},#{director},#{actor})")
    public void addMovie(Movies movie);

    //删除电影
    @Delete("delete from movie_list where id=#{id}")
    public void deleteMovieById(Integer id);

    //修改电影信息
    @Update("update movie_list set name=#{name},director=#{director},actor=#{actor} where id=#{id}")
    public void modifyMovie(Movies movie);


}

在TestMybatis 中添加测试方法:

package cn.txl.test;

import cn.txl.dao.IMoviesDao;
import cn.txl.domain.Movies;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestMybatis {

    @Autowired
    private IMoviesDao dao;

    //查询所有电影
    @Test
    public void testFindAll(){
        List<Movies> movies=dao.findAll();
        for(Movies movie:movies){
            System.out.println(movie);
        }
    }


    //根据id查询电影
    @Test
    public void testFindMovieById(){
        Integer id=2;
        System.out.println(dao.findMovieById(id));
    }

    //增加电影
    @Test
    public void testAddMovie(){
        Movies movie=new Movies();
        movie.setName("八恶人");
        movie.setDirector("塞缪尔杰克逊");
        dao.addMovie(movie);
    }

    //删除电影电影
    @Test
    public void testdeleteMovieById(){
        Integer id=7;
        dao.deleteMovieById(id);
    }

    //修改电影
    @Test
    public void testModifyMovie(){
        Movies movie=dao.findMovieById(7);
        movie.setDirector("昆汀");
        movie.setActor("塞缪尔杰克逊");
        dao.modifyMovie(movie);
    }



}

执行根据id查询:
在这里插入图片描述

执行增加电影方法:
在这里插入图片描述
执行修改电影方法:
在这里插入图片描述
执行删除电影方法:
在这里插入图片描述
doa层方法已经添加成功,然后添加service层的相关方法
在IMoviesService 接口添加增删改查方法:

package cn.txl.service;

import cn.txl.domain.Movies;
import java.util.List;

public interface IMoviesService {

    //查询所有电影
    public List<Movies> findAll();

    //根据id查询电影
    public Movies findMovieById(Integer id);

    //增加电影
    public void addMovie(Movies movie);

    //删除电影
    public void deleteMovieById(Integer id);

    //修改电影信息
    public void modifyMovie(Movies movie);

}

在MoviesServiceImpl 中实现接口方法,并根据正确的业务逻辑补充方法体

package cn.txl.service.impl;




import cn.txl.dao.IMoviesDao;
import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("moviesService")
public class MoviesServiceImpl implements IMoviesService {

    @Autowired
    private IMoviesDao dao;

    @Override
    public List<Movies> findAll() {
        System.out.println("MoviesServiceImpl的findAll方法执行了.............");
        return dao.findAll();
    }

    @Override
    public Movies findMovieById(Integer id) {
        return dao.findMovieById(id);
    }

    @Override
    public void addMovie(Movies movie) {
        dao.addMovie(movie);
    }

    @Override
    public void deleteMovieById(Integer id) {
        dao.deleteMovieById(id);
    }

    @Override
    public void modifyMovie(Movies movie) {
        dao.modifyMovie(movie);
    }
}

在TestSpring 补充相关测试方法:

package cn.txl.test;


import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring {

    @Autowired
    private IMoviesService service;

//    查询所有
    @Test
    public void tsetFindAll(){
        List<Movies> movies=service.findAll();
        for(Movies movie:movies){
            System.out.println(movie);
        }
    }

    //根据id查询电影
    @Test
    public void testFindMovieById(){
        Integer id=5;
        System.out.println(service.findMovieById(id));
    }

    //增加电影
    @Test
    public void testAddMovie(){
        Movies movie=new Movies();
        movie.setName("电锯惊魂");
        movie.setDirector("温子仁");
        movie.setActor("雷沃纳尔");
        service.addMovie(movie);
    }

    //删除电影电影
    @Test
    public void testdeleteMovieById(){
        Integer id=1;
        service.deleteMovieById(id);
    }

    //修改电影
    @Test
    public void testModifyMovie(){
        Movies movie=service.findMovieById(2);
        movie.setActor("张国荣、张曼玉、林青霞、张家辉等");
        service.modifyMovie(movie);
    }


}

执行根据id查询方法:
在这里插入图片描述
执行增加电影方法:
在这里插入图片描述
执行修改电影方法:
在这里插入图片描述
执行删除电影方法:
在这里插入图片描述
service层的增删改查方法也已经完成,接下来到controller补充

在MoviesController 里添加增删改查方法:

package cn.txl.controller;

import cn.txl.domain.Movies;
import cn.txl.service.IMoviesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/moviesController")
public class MoviesController {

    @Autowired
    private IMoviesService service;

//    查询所有
    @RequestMapping("findAll")
    public String findAll(Model model){
        List<Movies> movies=service.findAll();
        model.addAttribute("movies",movies);
        return "success";
    }


//    根据id查询一个
    @RequestMapping("findOne")
    public String findOne(Integer id,Model model){
        Movies movie=service.findMovieById(id);
        model.addAttribute("movie",movie);
        return "success";
    }


//    添加电影
    @RequestMapping("addMovie")
    public String addMovie(Movies movie,Model model){
        service.addMovie(movie);
        return "success";
    }

//    修改电影
    @RequestMapping("modifyMovie")
    public String modifyMovie(Movies movie,Model model){
        service.modifyMovie(movie);
        return "success";
    }


    //    删除电影
    @RequestMapping("deleteMovie")
    public String deleteMovie(Integer id,Model model){
        service.deleteMovieById(id);
        return "success";
    }
}

在index.jsp做如下修改:

<%--
  Created by IntelliJ IDEA.
  User: txllg
  Date: 2020/7/28
  Time: 10:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="moviesController/findAll">findAll方法</a><br>

根据id查询
<form action="moviesController/findOne">
   id:<input type="text" name="id"><br>
    <input type="submit" value="提交">
</form><br>

添加电影
<form action="moviesController/addMovie">
    name:<input type="text" name="name"><br>
    director:<input type="text" name="director"><br>
    actor:<input type="text" name="actor"><br>
    <input type="submit" value="提交">
</form><br>


修改电影
<form action="moviesController/modifyMovie">
    id:<input type="text" name="id"><br>
    name:<input type="text" name="name"><br>
    director:<input type="text" name="director"><br>
    actor:<input type="text" name="actor"><br>
    <input type="submit" value="提交">
</form><br>


删除电影
<form action="moviesController/deleteMovie">
    id:<input type="text" name="id"><br>
    <input type="submit" value="提交">
</form>

</body>
</html>

在success.jsp做如下修改,输出查询一个的结果:

<%--
  Created by IntelliJ IDEA.
  User: txllg
  Date: 2020/7/28
  Time: 14:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--添加jstl核心库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>congratulations!</h1>

<%--输出查询所有结果--%>
<c:forEach items="${movies}" var="movie">
    ${movie.id}-
    ${movie.name}-
    ${movie.director}-
    ${movie.actor}<br>

</c:forEach>


<%--输出查询一个结果--%>
${movie.id}--
${movie.name}--
${movie.director}--
${movie.actor}
</body>
</html>

开始测试添加的方法,启动tomcat服务器

根据id查询单个电影

根据id查询表单处输入:
在这里插入图片描述

在查询id处输入3,点击提交,结果如下:
在这里插入图片描述

在测试完这个方法后,把success.jsp的输出全部注掉,不然测试后面的方法程序会出错会,如下:

<%--
  Created by IntelliJ IDEA.
  User: txllg
  Date: 2020/7/28
  Time: 14:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%--添加jstl核心库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>congratulations!</h1>

<%--输出查询所有结果--%>
<%--<c:forEach items="${movies}" var="movie">--%>
<%--    ${movie.id}---%>
<%--    ${movie.name}---%>
<%--    ${movie.director}---%>
<%--    ${movie.actor}<br>--%>

<%--</c:forEach>--%>


<%--&lt;%&ndash;输出查询一个结果&ndash;%&gt;--%>
<%--${movie.id}----%>
<%--${movie.name}----%>
<%--${movie.director}----%>
<%--${movie.actor}--%>
<%--</body>--%>
</html>


添加电影

添加电影表单处输入:
在这里插入图片描述
点击提交:
在这里插入图片描述
数据库:
在这里插入图片描述


修改方法

修改电影表单处输入:
在这里插入图片描述

点击提交:
在这里插入图片描述
数据库:
在这里插入图片描述


删除电影项

删除电影表单处输入id:
在这里插入图片描述

点击提交:
在这里插入图片描述
数据库:
在这里插入图片描述
到这里,补充添加方法就完成了,这就是一个简单的SSM整合的小案例。

9.项目完整源码

源码地址:github

  • 37
    点赞
  • 121
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值