Spring+SpringMVC+MyBatis整合实战(SSM框架)

在写代码之前我们先了解一下这三个框架分别是干什么的?

SpringMVC

它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只返回json/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!!

Spring

太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。

MyBatis

如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦~捂脸~)编写的代码能搞提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。

项目结构

Spring+SpringMVC+MyBatis整合实战(SSM框架)_第1张图片

maven配置文件pom.xml




  4.0.0

  com.neu
  spring-over
  1.0-SNAPSHOT
  war

  spring-over Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
  

  
    
    
      org.springframework
      spring-context
      5.0.5.RELEASE
    
    
      org.aspectj
      aspectjweaver
      1.8.7
    
    
      org.springframework
      spring-jdbc
      5.0.5.RELEASE
    
    
      org.springframework
      spring-tx
      5.0.5.RELEASE
    
    
      org.springframework
      spring-test
      5.0.5.RELEASE
    
    
      org.springframework
      spring-webmvc
      5.0.5.RELEASE
    

    
    
      javax.servlet
      servlet-api
      2.5
    
    
      javax.servlet.jsp
      jsp-api
      2.0
    

    
    
      org.mybatis
      mybatis
      3.4.5
    
    
      org.mybatis
      mybatis-spring
      1.3.1
    
    
      mysql
      mysql-connector-java
      5.1.44
    
    
      c3p0
      c3p0
      0.9.1.2
    

    
      junit
      junit
      4.12
    
    
      jstl
      jstl
      1.2
    

  

  
    sprig-over
    
      
        
          maven-clean-plugin
          3.0.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.7.0
        
        
          maven-surefire-plugin
          2.20.1
        
        
          maven-war-plugin
          3.2.0
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  


webapp配置文件web.xml




  
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
    org.springframework.web.context.ContextLoaderListener
  

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



spring配置文件applicationContext.xml




    
    
        
        
    

    
    

    
    
        
        
        
        
    

    
    
        
        
        
    

    
    
        
    

    
    
    
        
    

    
    
        
            
        
    

    
    
        
    


spring-mvc配置文件spring-mvc.xml




    
    
    
    
    
    
        
        
    
    
    

mybatis映射文件AccountMapper.xml




    
        insert into account(id,name,money) values(#{id},#{name},#{money})
    

    


mybatis配置文件(两种整合方法)

1.sqlMapConfig.xml直接引入





    
    

    
        
        
    

    
    
        
            
            
                
                
                
                
            
        
    

    
    
        
    

引入方法

public void save(Account account) {
        try {
            //加载配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            //构建会话工厂
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            //创建连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //获取映射对象
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            //执行方法
            mapper.save(account);
            //提交连接
            sqlSession.commit();
            //关闭连接
            sqlSession.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

2.sqlMapConfig-spring.xml使用spring构建连接

sqlMapConfig-spring.xml





    
        
        
    

    
    
        
    


spring配置注入


    

    
    
        
        
        
        
    

    
    
        
        
        
    

    
    
        
    

    
    
    
        
    

    
    
        
            
        
    

    
    
        
    

注入代码

@Autowired
private AccountMapper accountMapper;


@Override
public void save(Account account) {
    accountMapper.save(account);
}

日志配置文件log4j.properties

#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or .
#

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=all, stdout

建表语句

create table account(
	id int primary key auto_increment,
	name varchar(100),
	money double(7,2)
)

Tomcat传递过程

1.网页获取表单

save.jsp

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


    Title


    

添加账户信息表单

账户名称:
账户金额:

Spring+SpringMVC+MyBatis整合实战(SSM框架)_第2张图片

2.Controller层处理请求

AccountController.java

package com.neu.controller;

import com.neu.domain.Account;
import com.neu.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String save(Account account){
        accountService.save(account);
        System.out.println(account);
        return "保存成功";
    }

    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        List accountList = accountService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("accountList",accountList);
        modelAndView.setViewName("accountList");
        return modelAndView;
    }
}

3.service层处理业务逻辑

AccountServiceimpl.java

package com.neu.service.impl;

import com.neu.domain.Account;
import com.neu.mapper.AccountMapper;
import com.neu.service.AccountService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

    @Autowired
    private AccountMapper accountMapper;


    @Override
    public void save(Account account) {
//        try {
//            //加载配置文件
//            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//            //构建会话工厂
//            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//            //创建连接
//            SqlSession sqlSession = sqlSessionFactory.openSession();
//            //获取映射对象
//            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
//            //执行方法
//            mapper.save(account);
//            //提交连接
//            sqlSession.commit();
//            //关闭连接
//            sqlSession.close();
//        } catch (IOException exception) {
//            exception.printStackTrace();
//        }
        accountMapper.save(account);
    }

    @Override
    public List findAll() {
//        try {
//            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//            SqlSession sqlSession = sqlSessionFactory.openSession();
//            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
//            List accountList = mapper.findAll();
//            sqlSession.close();
//            return accountList;
//        } catch (IOException exception) {
//            exception.printStackTrace();
//        }
        return accountMapper.findAll();
    }
}

4.mapper与数据库交互
mapper层对数据库进行数据持久化操作,他的方法语句是直接针对数据库操作的,主要实现一些增删改查操作,在mybatis中方法主要与与xxx.xml内相互一一映射

AccountMapper.java

package com.neu.mapper;

import com.neu.domain.Account;

import java.util.List;

public interface AccountMapper {

    public void save(Account account);

    public List findAll();
}

到此这篇关于Spring+SpringMVC+MyBatis整合实战(SSM框架)的文章就介绍到这了,更多相关Spring SpringMVC MyBatis整合 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Spring+SpringMVC+MyBatis整合实战(SSM框架))