IDEA整合Maven+SSM框架

0 前言

参考资料《史上最详细的IDEA优雅整合Maven+SSM框架(详细思路+附带源码)

1 搭建整合环境

1.1 整合说明

整合说明:SSM整合可以使用多种方式,咱们选择XML + 注解的方式,不要觉得不妥,这样其实最便捷-

1.2 整合的思路

1、搭建整合的环境
2、把Spring的配置搭建完成
3、使用Spring整合SpringMVC框架
4、再把MyBatis的配置搭建完成
5、之后使用Spring整合MyBatis框架
6、最后s整合Spring的声明式事务管理

1.3 创建数据库和表结构

复制在MySQL中运行即可:
create database ssm;
use ssm;
create table account (
id int primary key auto_increment,
name varchar(50),
money double
);

1.4 创建有骨架 java工程

1、使用IntelliJ IDEA创建有骨架的Mawen项目

在这里插入图片描述

2、 补全GroupId和ArtifactId

在这里插入图片描述

3、指定本地的maven仓库

在这里插入图片描述

4、指定工程位置,点击finish完成项目创建

在这里插入图片描述
5、新创建的项目pom.xml中会产生很多多余的配置,可以直接删除,maven默认编译为1.7

在这里插入图片描述
6、补全java目录,resources目录和test目录,标准web工程目录结构如下

在这里插入图片描述
1.5 在pom.xml文件中引入ssm整合坐标依赖

版本控制是在< properties >标签中控制,从坐标依赖中可以看出版本号:spring5X、MySQL5.1.6、mybatis3.4.5、编译环境使用JDK1.8、配置tomcat7插件

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

  <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.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <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 -->
    <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>
    <plugins>
      <!-- 配置Tomcat插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <!--配置端口号-->
          <port>8080</port>
          <!--配置项目路径-->
          <path>/ssm</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

1.6 在resources资源文件编写日志配置文件
编写log4j.properties

log4j.rootLogger=DEBUG,stdout
log4j.logger.com.ibatis=DEBUG

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ssS} %m%n

1.7 测试tomcat插件

在这里插入图片描述
启动成功如下图
在这里插入图片描述

2 Spring框架代码的编写

2.1 编写实体类
在dto包中编写Account的实体类,实体类的属性与数据库保持一致

package com.itcast.dto;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    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 Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2.2 编写dao接口
在dao包中编写dao接口IAccountDao

package com.itcast.dao;

import com.itcast.dto.Account;

public interface IAccountDao {

    /**
     * 根据name查询账户
     * @return
     */
    Account findAccountByName(String name);

    /**
     * 根据name更新账户
     * @param account
     * @return
     */
    Boolean updateAccount(Account account);
}

2.3 编写service接口和实现类
service接口:

package com.itcast.service;

import com.itcast.dto.Account;

public interface AccountService {
    /**
     * 根据name查询账户
     * @param name
     * @return
     */
    Account findAccountByName(String name);

    /**
     * 根据name更新账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 模拟银行转账
     * @param sourceName
     * @param targetName
     * @param money
     */
    void transfer(String sourceName, String targetName, Float money);
}

service接口实现类:

package com.itcast.service.Impl;

import com.itcast.dto.Account;
import com.itcast.service.AccountService;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Override
    public Account findAccountByName(String name) {
        System.out.println("Service业务层:根据name查询账户...");
        return null;
    }
    
    @Override
    public void updateAccount(Account account) {
        System.out.println("Service业务层:根据name更新账户...");
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("Service业务层:模拟银行账户转账...");
    }
}

2.4 resources资源文件编写Spring的配置文件applicationContext.xml
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">

    <!-- 1.开启注解的扫描,希望处理业务层service和持久层dao,表现层controller不希望spring去处理 -->
    <context:component-scan base-package="com.itcast">
        <!-- 配置controller注解不扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

2.5 在项目中编写测试方法,进行测试
在test包中创建一个叫TestSpring的class类,具体的内容如下

package com.itcast.test;

import com.itcast.dto.Account;
import com.itcast.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void run1(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        AccountService as = (AccountService) ac.getBean("accountService");
        Account account = as.findAccountByName("Spring1");
        System.out.println(account);
    }
}

运行如下效果,说明搭建Spring的开发环境成功!
在这里插入图片描述
到这里,Spring的开发环境成功!接下来搭建SpringMVC框架环境。

3 SpringMVC框架代码的编写

搭建和测试SpringMVC的开发环境
3.1 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>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器时,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</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>

3.2 创建springmvc.xml的配置文件,编写配置文件
同样是在resources资源文件夹中创建springmvc.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" 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/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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--1.开启注解扫描,只扫描controller注解-->
    <context:component-scan base-package="com.itcast">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--2.配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--3.过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/images/" mapping="/images/**" />

    <!--4.开启springmvc注解的支持-->
    <mvc:annotation-driven />
</beans>

3.3 创建jsp页面,并编写controller代码
编写index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ssm整合</title>
</head>
<body>
    <h2>1、根据accountName查询一个账户</h2>
    <form action="account/findAccountByName" method="get">
        账户姓名:<input type="text" name="accountName"></input> <br>
        <input type="submit" name="submit" value="提交">
    </form>
    <hr/>
    <h2>2、根据accountName更新账户</h2>
    <form action="account/updateAccount" method="post">
        账户姓名:<input type="text" name="name"></input> <br>
        账户金额:<input type="text" name="money"></input> <br>
        <input type="submit" name="submit" value="提交">
    </form>
    <hr/>
    <h2>3、模拟银行账户转账</h2>
    <form action="account/transfer" method="post">
        转出账户:<input type="text" name="sourceName"></input> <br>
        转入账户:<input type="text" name="targetName"></input> <br>
        账户金额:<input type="text" name="money"></input> <br>
        <input type="submit" name="submit" value="提交">
    </form>
</body>
</html>

在controller层中的AccountController的class类中编写代码

package com.itcast.controller;

import com.itcast.dto.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AccountController {

    @RequestMapping("/account/findAccountByName")
    public String findAccountByName(String accountName){
        System.out.println(accountName);
        System.out.println("Controller表现层:根据accountName查询一个账户...");
        return "success";
    }

    @RequestMapping("/account/updateAccount")
    public String updateAccount(Account account) {
        System.out.println(account);
        System.out.println("Service业务层:根据name更新账户...");
        return "success";
    }

    @RequestMapping("/account/transfer")
    public String transfer(String sourceName, String targetName, Float money) {
        System.out.println(sourceName);
        System.out.println(targetName);
        System.out.println(money);
        System.out.println("Service业务层:模拟银行账户转账...");
        return "success";
    }
}

3.4 创建controller跳转的success.jsp页面
WEB-INF下创建目录pages,在springmvc中已经配置视图解析器

<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
</bean>

编写success.jsp页面

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

<html>
<head>
    <title>Title</title>
</head>
<body>
    <h2>成功</h2>
</body>
</html>

3.5 使用maven的Tomcat7插件启动项目进行测试
1、双击IDEA–>Maven–>tomcat7:rum

在这里插入图片描述
2、项目启动成功

在这里插入图片描述
3、验证参数绑定成功

在这里插入图片描述
到这里,springmvc的开发环境就都搭建好了

4 Spring整合SpringMVC的框架

4.1 Spring整合SpringMVC的框架原理分析

整合成功的表现:在controller(SpringMVC)中能成功的调用service(Spring)对象中的方法。要想在controller中调用service方法,就要注入service到controller中来,有service对象才可以调用service方法,方法是这样没有错,但是有一个问题,就是启动Tomcat之后试想一下,在web.xml中配置有前端控制器,web容器会帮我们加载springmvc.xml配置文件,在springmvc.xml配置文件中我们配置情况是只扫描controller,别的不扫,而applicationContext.xml文件就从头到尾没有执行过,applicationContext中的配置扫描自然也不会去扫描,就相当于没有将applicationContext交到IOC容器当中去,所以,现在的解决方案就是,在启动服务器时就加载applicationContext配置文件,怎么实现呢?这时候监听器listener就派上用场了,具体实现如下:

在这里插入图片描述
在web.xml中配置ContextLoaderListener监听器

<!--配置Spring的监听器,默认只加载WEB-INF目录下的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>

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

  <!--applicationContext配置文件-->
  <!--配置监听器,默认只加载web-inf目录下的applicationContext.xml-->
  <!--但是我们的文件在resources文件夹下-->
  <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>

  <!--配置前端控制器-->
  <servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器时,创建该servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-dispatcher</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>

4.3 controller中注入service对象,调用service对象方法并测试

这时候,启动服务器时也会加载spring配置文件了,那么,我们可以在controller中注入service了,于是开始编写controller代码:

package com.itcast.controller;

import com.itcast.dto.Account;
import com.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AccountController {

    @Autowired   //按类型注入
    private AccountService accountService;

    @RequestMapping("/account/findAccountByName")
    public String findAccountByName(String accountName){
        System.out.println("Controller表现层:根据accountName查询一个账户...");
        Account account = accountService.findAccountByName(accountName);
        return "success";
    }

    @RequestMapping("/account/updateAccount")
    public String updateAccount(Account account) {
        System.out.println("Controller表现层:根据name更新账户...");
        accountService.updateAccount(account);
        return "success";
    }

    @RequestMapping("/account/transfer")
    public String transfer(String sourceName, String targetName, Float money) {
        System.out.println("Controller表现层:模拟银行账户转账...");
        accountService.transfer(sourceName,targetName,money);
        return "success";
    }
}

编写完成,开始测试,启动Maven的Tomcat插件

在这里插入图片描述
到这里整合完了spring、springmvc

5 MyBatis框架代码的编写

MyBatis环境搭建首先是dao,搭建mybatis,之前要编写mapper映射的配置文件
5.1 IAccountDao接口编写

package com.itcast.dao;

import com.itcast.dto.Account;

public interface IAccountDao {

    /**
     * 根据name查询账户
     * @return
     */
    Account findAccountByName(String name);

    /**
     * 根据name更新账户
     * @param account
     * @return
     */
    Boolean updateAccount(Account account);
}

5.2 编写mapper映射的配置文件
在resources文件夹下创建目录mapping,然后创建映射文件AccountMapper.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.itcast.dao.IAccountDao">
    <!--根据name查询账户-->
    <select id="findAccountByName" parameterType="String" resultType="com.itcast.dto.Account">
        select * from account where name = #{s_id};
    </select>

    <!--根据name更新账户-->
    <update id="updateAccount" parameterType="com.itcast.dto.Account">
        update account set money = #{money} where name = #{name};
    </update>

</mapper>

5.3 创建SqlMapConfig.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>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.134.66:3306/ssm"/>
                <property name="username" value="root"/>
                <property name="password" value="root123"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
    <mappers>
        <mapper resource="mapping/AccountMapper.xml"/>
    </mappers>
</configuration>

5.4 创建并编写Mybatis测试方法
测试方法TestMyBatis

package com.itcast.test;

import com.itcast.dao.IAccountDao;
import com.itcast.dto.Account;
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.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {

    @Test
    public void run1() throws IOException {
        Account account =new Account();
        account.setName("ss");
        account.setMoney(201d);
        // 加载配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建SqlSession对象
        SqlSession session = factory.openSession();
        // 获取到代理对象
        IAccountDao dao = session.getMapper(IAccountDao.class);
        // update
        dao.updateAccount(account);
        // 提交事务
        session.commit();
        // 关闭资源
        session.close();
        in.close();
    }

    @Test
    public void run2() throws Exception {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        IAccountDao dao = session.getMapper(IAccountDao.class);
        Account account = dao.findAccountByName("Spring1");
        System.out.println(account);
        session.close();
        in.close();
    }
}

到这里,mybatis环境搭建算是完成了

6 Spring整合MyBatis框架

Spring整合MyBatis框架之前,先想一想,怎样才算整合成功呢?其实,这和之前的spring整合springMVC的套路差不多,其实就是,Service能成功调用dao对象,能够做查询操作或者新增数据能存进数据库。现在spring已经是在IOC容器中了,dao是一个接口,可以通过程序帮这个接口生成代理对象,我们要是可以把这个代理对象也放进IOC容器,那么service就可以拿到这个对象,之后在service中做一个注入,service从而调用dao代理对象的方法,那么我们怎么去实现dao接口生成的代理对象放入IOC容器呢?其实很简单,只需要如下操作!
整合目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中

1、在applicationContext.xml中配置数据库连接池
2.、在applicationContext.xml中配置SqlSessionFactory工厂

没配置工厂之前,我们用Test测试的时候,每次都要先创建工厂,因为工厂能够给我们创建SqlSession,有了SqlSession就可以通过SqlSession拿到代理对象。现在我们直接在applicationContext.xml中配置SqlSessionFactory工厂,这就相当于IOC容器中有了工厂,就可以去创建SqlSession,进而通过SqlSession拿到代理对象,没必要每次测试都去创建工厂。

3、在applicationContext.xml中配置IAccountDao接口所在包

因为工厂有了,SqlSession也有了,那代理谁呢,所以我们要配置IAccountDao接口所在包,告诉SqlSession去代理接口所在包中的代理,从而存到IOC容器中.其实,上面的操作就是把mybatis中的配置(SqlMapConfig.xml)转移到spring中去,让它产生代理并存到IOC容器中!

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

    <!-- 1.开启注解的扫描,希望处理业务层service和持久层dao,表现层controller不希望spring去处理 -->
    <context:component-scan base-package="com.itcast">
        <!-- 配置controller注解不扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 2.Spring整合Mybatis框架 -->
    <!-- 2.1 配置连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://192.168.134.66:3306/ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="root123"/>
    </bean>

    <!-- 2.2 配置sqlSessionFactory工厂 -->
    <bean id="sqlSessonFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapping/*.xml" />
    </bean>

    <!-- 2.3 DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itcast.dao"/>
    </bean>
</beans>

5、完善Service层代码
在AccountServiceImpl实现类中编写代码:

package com.itcast.service.Impl;

import com.itcast.dao.IAccountDao;
import com.itcast.dto.Account;
import com.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountByName(String name) {
        System.out.println("Service业务层:根据name查询账户...");
        return accountDao.findAccountByName(name);
    }

    @Override
    public void updateAccount(Account account) {
        System.out.println("Service业务层:根据name更新账户...");
        accountDao.updateAccount(account);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("Service业务层:模拟银行账户转账...");
// 1. 根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        // 2. 根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        // 3. 转出账户减钱
        source.setMoney(source.getMoney() - money);
        // 4. 转入账户加钱
        target.setMoney(target.getMoney() + money);
        // 5. 更新转出账户
        accountDao.updateAccount(source);
//        int i=1/0;
        //2.6更新转入账户
        accountDao.updateAccount(target);
    }
}

6、运行测试

在web页面模拟银行账户转账,在数据库查看账户金额的变化(初始化金额都是100),账户Spring3变成90,Spring4变成110

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

到这里,SSM整合就基本完成,接下来,spring整合mybatis框架还需要配置事务

7 Spring的声明式事务管理

spring配置事务管理的目的是在提交数据库发生异常时回滚事务,保持数据的一致性
7.1 在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">

    <!-- 1.开启注解的扫描,希望处理业务层service和持久层dao,表现层controller不希望spring去处理 -->
    <context:component-scan base-package="com.itcast">
        <!-- 配置controller注解不扫描 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 2.Spring整合Mybatis框架 -->
    <!-- 2.1 配置连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://192.168.134.66:3306/ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="root123"/>
    </bean>

    <!-- 2.2 配置sqlSessionFactory工厂 -->
    <bean id="sqlSessonFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapping/*.xml" />
    </bean>

    <!-- 2.3 DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itcast.dao"/>
    </bean>

    <!-- 3.配置spring框架声明式事务管理器 -->
    <!-- 3.1配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 3.2配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT" />
        </tx:attributes>
    </tx:advice>
    <!--3.3配置AOP增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itcast.service.Impl.*ServiceImpl.*(..))" />
    </aop:config>
</beans>

7.2 完善Service层,模拟转账方法上加上1/0异常
AccountServiceImpl的代码如下

package com.itcast.service.Impl;

import com.itcast.dao.IAccountDao;
import com.itcast.dto.Account;
import com.itcast.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountByName(String name) {
        System.out.println("Service业务层:根据name查询账户...");
        return accountDao.findAccountByName(name);
    }

    @Override
    public void updateAccount(Account account) {
        System.out.println("Service业务层:根据name更新账户...");
        accountDao.updateAccount(account);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("Service业务层:模拟银行账户转账...");
        // 1. 根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        // 2. 根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        // 3. 转出账户减钱
        source.setMoney(source.getMoney() - money);
        // 4. 转入账户加钱
        target.setMoney(target.getMoney() + money);
        // 5. 更新转出账户
        accountDao.updateAccount(source);
        int i=1/0;
        //2.6更新转入账户
        accountDao.updateAccount(target);
    }
}

7.3 测试spring的事务配置
1、检查数据库的账户数据
在这里插入图片描述
2、在web页面模拟银行转账
在这里插入图片描述
3、检查数据库的账户数据
在这里插入图片描述

此时,发现事务管理失效,在提交事务发生异常时没有回滚

7.3 Spring声明式事务失效问题解决
问题原因是springmvc.xml的配置文件和applicationContext.xml的配置文件配置的注解扫描包冲突,导致spring事务失效
在这里插入图片描述
在这里插入图片描述
解决方法为修改springmvc.xml扫描包,配置只扫描controller下的包
完整的springmvc如下

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

    <!--1.开启注解扫描,只扫描controller注解-->
    <context:component-scan base-package="com.itcast.controller">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--2.配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--3.过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/images/" mapping="/images/**" />

    <!--4.开启springmvc注解的支持-->
    <mvc:annotation-driven />
</beans>

7.4 事务测试
1、双击maven的tomcat插件
2、模拟银行转账
在这里插入图片描述
3、由于代码中存在异常,提交失败回滚
在这里插入图片描述
4、检查数据库

在这里插入图片描述
至此,Spring的声明式事务管理生效
ssm整合全部完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值