Spring+SpringMVC+Mybatis 整合

我的环境

idea 2019.1
jdk 1.8
Spring 5
Lombok插件 这里是使用和安装链接(包括idea和eclipse) @简单粗暴节省JavaBean代码插件 Lombok.jar


整合 Spring+SpringMVC+Mybatis 之前需要学习的
Mybatis篇
@初识mybatis的配置文件以及命名之坑和注解
Spring篇
@Spring知识点整合(上)
@Spring知识点整合(中)
@Spring知识点整合(下)
SpringMVC篇
@SpringMVC知识点整合(上)
@SpringMVC知识点整合(下)


A. 搭建整合环境 *** 重要
1. 整合说明:SSM整合可以使用多种方式,我此处会选择XML + 注解的方式 注意是使用Spring整合其他两个框架
2. 整合的思路
  1. 先搭建整合的环境
  2. 先把Spring的配置搭建完成
  3. 再使用Spring整合SpringMVC框架
  4. 最后使用Spring整合MyBatis框架
3. 创建数据库和表结构

建立表

create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
4. 创建maven的工程(今天会使用到工程的聚合和拆分的概念,这个技术maven高级会讲) 我之后会写一篇
  1. 创建ssm_parent父工程(打包方式选择pom,必须的)
  2. 创建ssm_web子模块(打包方式是war包)
  3. 创建ssm_service子模块(打包方式是jar包)
  4. 创建ssm_dao子模块(打包方式是jar包)
  5. 创建ssm_domain子模块(打包方式是jar包)
  6. web依赖于service,service依赖于dao,dao依赖于domain
  7. 在ssm_parent的pom.xml文件中引入坐标依赖
    版本锁定
5.0.2.RELEASE
1.6.6
1.2.12
5.1.6
3.4.5

依赖的坐标


    
    
        org.aspectj
        aspectjweaver
        1.6.8
    
    
        org.springframework
        spring-aop
        ${spring.version}
    
    
        org.springframework
        spring-context
        ${spring.version}
    
    
        org.springframework
        spring-web
        ${spring.version}
    
    
        org.springframework
        spring-webmvc
        ${spring.version}
    
    
        org.springframework
        spring-test
        ${spring.version}
    
    
        org.springframework
        spring-tx
        ${spring.version}
    
    
        org.springframework
        spring-jdbc
        ${spring.version}
    
    
        junit
        junit
        4.12
        compile
    
    
        mysql
        mysql-connector-java
        ${mysql.version}
    
    
        javax.servlet
        servlet-api
        2.5
        provided
    
    
        javax.servlet.jsp
        jsp-api
        2.0
        provided
    
    
        jstl
        jstl
        1.2
    
    
    
        log4j
        log4j
        ${log4j.version}
    
    
        org.slf4j
        slf4j-api
        ${slf4j.version}
    
    
        org.slf4j
        slf4j-log4j12
        ${slf4j.version}
    
    
    
        org.mybatis
        mybatis
        ${mybatis.version}
    
    
        org.mybatis
        mybatis-spring
        1.3.0
    
    
        c3p0
        c3p0
        0.9.1.2
        jar
        compile
    
    
    
        org.projectlombok
        lombok
        1.18.8
        provided
    

  1. 部署ssm_web的项目,只要把ssm_web项目加入到tomcat服务器中即可
5.编写实体类

Account.java

package cn.icanci.domain;

import lombok.Data;

import java.io.Serializable;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.domain
 * @Date: Created in 2020/1/15 13:22
 * @ClassAction: 账户
 */
@Data
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;
}
6.编写dao接口

IAccountDao.java

package cn.icanci.dao;

import cn.icanci.domain.Account;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.dao
 * @Date: Created in 2020/1/15 13:26
 * @ClassAction: 账户Dao的接口
 */
public interface IAccountDao {

    /**
     * 查询所有的账户信息
     * @return 返回泛型为 Account的List集合
     */
    public List findAllAccount();

    /**
     * 保存账户的信息
     * @param account 需要保存的账户
     */
    public void saveAccount(Account account);
}
7.编写service接口和实现类

IAccountService .java

package cn.icanci.service;

import cn.icanci.domain.Account;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.service
 * @Date: Created in 2020/1/15 13:29
 * @ClassAction:
 */
public interface IAccountService {
    /**
     * 查询所有的账户信息
     * @return 返回泛型为 Account的List集合
     */
    public List findAllAccount();

    /**
     * 保存账户的信息
     * @param account 需要保存的账户
     */
    public void saveAccount(Account account);
}

AccountServiceImpl.java

package cn.icanci.service.impl;

import cn.icanci.domain.Account;
import cn.icanci.service.IAccountService;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.service.impl
 * @Date: Created in 2020/1/15 13:29
 * @ClassAction:
 */
public class AccountServiceImpl implements IAccountService {
    @Override
    public List findAllAccount() {
        System.out.println("业务层查询所有的账户信息");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层保存账户信息");
    }
}
B. Spring框架代码的编写
1. 在ssm_web项目中创建applicationContext.xml的配置文件,编写具体的配置信息。

applicationContext.xml





    
    
        
        
    

2. 导入log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=E:/AllLogs/idea2019/maven/ssm/ssm.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
3. 在ssm_web项目中编写测试方法,进行测试

TestAccountServiceImpl.java

package cn.icanci.test;

import cn.icanci.domain.Account;
import cn.icanci.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.test
 * @Date: Created in 2020/1/15 13:48
 * @ClassAction: 测试 AccountServiceImpl
 */
public class TestAccountServiceImpl {
    @Test
    public void run1(){
        //加载配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取对象
        IAccountService accountService = ac.getBean("accountService",IAccountService.class);
        //调用方法
        accountService.findAllAccount();
        accountService.saveAccount(new Account());
    }
}

控制台打印

业务层查询所有的账户信息
业务层保存账户信息
C. 配置 SpringMVC 的环境

web.xml的配置




  Archetype Created Web Application

  
    DispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      classpath:springmvc.xml
    
    
    1
  
  
    DispatcherServlet
    /
  
  
  
    characterEncodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      UTF-8
    
  
  
    characterEncodingFilter
    /*
  

springmvc.xml




    
    
        
        
    
    
    
        
        
    
    
    
    
    
    
    

前端界面

index.jsp

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


    测试


    测试SpringMVC环境


/WEB-INF/pages/list.jsp

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


    list


    testFindAllAccount


账户的web层 AccountController.java

package cn.icanci.controller;

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

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.controller
 * @Date: Created in 2020/1/15 13:32
 * @ClassAction: 账户的web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    @RequestMapping("/findAllAccount")
    public String findAllAccount(){
        System.out.println("AccountController.findAllAccount");
        return "list";
    }
}

测试


Spring+SpringMVC+Mybatis 整合_第1张图片
测试通过
D. Spring整合SpringMVC的框架
  1. 目的:在controller中能成功的调用service对象中的方法。
  2. 在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。
    只需要在web.xml中配置如下 监听器
 
    
        org.springframework.web.context.ContextLoaderListener
    
    
    
        contextConfigLocation
        classpath:applicationContext.xml
    
  1. 在controller中注入service对象,调用service对象的方法进行测试
    AccountController.java
package cn.icanci.controller;

import cn.icanci.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.controller
 * @Date: Created in 2020/1/15 13:32
 * @ClassAction: 账户的web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAllAccount")
    public String findAllAccount(){
        System.out.println("AccountController.findAllAccount");
        //调用Service的方法
        accountService.findAllAccount();
        return "list";
    }
}

测试结果


Spring+SpringMVC+Mybatis 整合_第2张图片
测试通过
E. Spring整合Mybatis框架
1. 搭建和测试MyBatis的环境
  1. 在web项目中编写SqlMapConfig.xml的配置文件,编写核心配置文件 SqlMapperConfig.xml



    
    
        
            
            
                
                
                
                
            
        
    

    
    
        

    

2.编写 sql语句的注解 IAccountDao.java

package cn.icanci.dao;

import cn.icanci.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.dao
 * @Date: Created in 2020/1/15 13:26
 * @ClassAction: 账户Dao的接口
 */
public interface IAccountDao {

    /**
     * 查询所有的账户信息
     *
     * @return 返回泛型为 Account的List集合
     */
    @Select("select * from account")
    List findAllAccount();

    /**
     * 保存账户的信息
     *
     * @param account 需要保存的账户
     */
    @Insert("insert into account (name,money) values (#{name},#{money})")
    void saveAccount(Account account);
}

3.测试 Mybatis
测试类 TestMybatis.java

package cn.icanci.test;

import cn.icanci.dao.IAccountDao;
import cn.icanci.domain.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;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.test
 * @Date: Created in 2020/1/15 14:55
 * @ClassAction:
 */
public class TestMybatis {
    @Test
    public void run1(){
        //加载配置文件
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapperConfig.xml");
            //创建SqlSessionFactory 对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建SqlSession对象
            SqlSession session = factory.openSession();
            //获得代理对象
            IAccountDao accountDao = session.getMapper(IAccountDao.class);
            List listAccount = accountDao.findAllAccount();
            for (Account account:listAccount) {
                System.out.println(account);
            }
            //关闭session链接
            session.close();
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void run2(){
        //加载配置文件
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapperConfig.xml");
            //创建SqlSessionFactory 对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建SqlSession对象
            SqlSession session = factory.openSession();
            //获得代理对象
            IAccountDao accountDao = session.getMapper(IAccountDao.class);
            //保存
            Account account = new Account();
            account.setName("table");
            account.setMoney(45645D);
            accountDao.saveAccount(account);
            //提交事务
            session.commit();
            //关闭session链接
            session.close();
            resourceAsStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("---------------------------------------------------------");
        run1();
    }
}

测试结果


Spring+SpringMVC+Mybatis 整合_第3张图片
测试通过
2. Spring整合Mybatis

修改 applicationContext.xml 把Mybatis相关的类交给Spring管理





    
    
        
        
    
    
    
    
        
        
        
        
    
    
    
        
    
    
    
        
    

给IAccountDao.java添加Spting管理的注解

package cn.icanci.dao;

import cn.icanci.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.dao
 * @Date: Created in 2020/1/15 13:26
 * @ClassAction: 账户Dao的接口
 */
@Repository("accountDao")
public interface IAccountDao {

    /**
     * 查询所有的账户信息
     *
     * @return 返回泛型为 Account的List集合
     */
    @Select("select * from account")
    List findAllAccount();

    /**
     * 保存账户的信息
     *
     * @param account 需要保存的账户
     */
    @Insert("insert into account (name,money) values (#{name},#{money})")
    void saveAccount(Account account);
}

修改 AccountServiceImpl.java

package cn.icanci.service.impl;

import cn.icanci.dao.IAccountDao;
import cn.icanci.domain.Account;
import cn.icanci.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.service.impl
 * @Date: Created in 2020/1/15 13:29
 * @ClassAction:
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;
    @Override
    public List findAllAccount() {
        System.out.println("业务层查询所有的账户信息");
        return accountDao.findAllAccount();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层保存账户信息");
        accountDao.saveAccount(account);
    }
}

修改 AccountControlle.java

package cn.icanci.controller;

import cn.icanci.domain.Account;
import cn.icanci.service.IAccountService;
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;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.controller
 * @Date: Created in 2020/1/15 13:32
 * @ClassAction: 账户的web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAllAccount")
    public String findAllAccount(Model model){
        System.out.println("AccountController.findAllAccount");
        //调用Service的方法
        List  accountList = accountService.findAllAccount();
        model.addAttribute("accountList",accountList);
        return "list";
    }
}

测试


Spring+SpringMVC+Mybatis 整合_第4张图片
测试通过
3. Spring整合Mybatis配置事务 配置Spring的声明式事务管理

配置 applicationContext.xml 文件




  
    
        
        
    
    
    
    
        
        
        
        
    
    
    
        
    
    
    
        
    

    
    
    
        
    
    
    
        
            
            
        
    
    
    
        
    

修改index.jsp

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


    测试


    测试SpringMVC环境
    
name:
money:

修改 AccountController,java

package cn.icanci.controller;

import cn.icanci.domain.Account;
import cn.icanci.service.IAccountService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: icanci
 * @ProjectName: ssm
 * @PackageName: cn.icanci.controller
 * @Date: Created in 2020/1/15 13:32
 * @ClassAction: 账户的web层
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @RequestMapping("/findAllAccount")
    public String findAllAccount(Model model){
        System.out.println("AccountController.findAllAccount");
        //调用Service的方法
        List  accountList = accountService.findAllAccount();
        model.addAttribute("accountList",accountList);
        return "list";
    }

    @RequestMapping("/saveOrUpdate")
    public void saveOrUpdate(Account account, HttpServletRequest req, HttpServletResponse resp){
        System.out.println("AccountController.saveOrUpdate");
        //调用Service方法
        accountService.saveAccount(account);
        try {
            resp.sendRedirect(req.getContextPath() + "/account/findAllAccount");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ;
    }
}

测试的时候 报错

Spring+SpringMVC+Mybatis 整合_第5张图片
报错

此处报错 需要增加一个 xsd依赖

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
Spring+SpringMVC+Mybatis 整合_第6张图片
增加此处依赖

测试


Spring+SpringMVC+Mybatis 整合_第7张图片
表单页面

Spring+SpringMVC+Mybatis 整合_第8张图片
查询页面
至此 Spring 整合 SpringMVC 和 Mybatis 已经完成

此处 @我自己 这是QQ聊天的链接 欢迎一起吹

你可能感兴趣的:(Spring+SpringMVC+Mybatis 整合)