Spring+SpringMVC+MyBatis详细整合过程

想要重新学习一下spring+mybatis,这次通过一个项目重新搭建了一次,这个过程中遇到的问题和解决方法顺便记录下。思路:学会搭建整个框架,把框架用起来,然后学习。

1.基本概念

1.1、Spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.2、SpringMVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

1.3、MyBatis

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

2.环境依赖

本项目的开发基于maven,tomcat,mysql,IDEA,JDK(6-8都行)等,因此想要在如下的代码中,整个项目最终顺利的跑起来需要事先准备以上环境,至于环境的配置,可以看其他的博客。

tomcat 7.0
IntelliJ IDEA 14.1.4
mysql 5.6
maven 3.1.0

3.SSM整合

1) 编写pom.xml 文件 引入所需要的jar包

"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/maven-v4_0_0.xsd">

    4.0.0
    com.hotel
    back-hotel
    war
    1.0-SNAPSHOT
    back-hotel

    
        4.1.1.RELEASE
        
        3.2.6
        
        1.7.7
        1.2.17
    

    
        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        
        
            org.springframework
            spring-oxm
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
            javax.servlet
            servlet-api
            2.5
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        

        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        

        
            javax.servlet.jsp
            jsp-api
            2.1
            provided
        



        
            org.springframework
            spring-test
            ${spring.version}
            test
        

        
            junit
            junit
            4.11
            test
        

        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
        
            org.mybatis
            mybatis-spring
            1.2.2
        
        
        
            javax
            javaee-api
            7.0
        
        
        
            mysql
            mysql-connector-java
            5.1.30
        
        
        
            commons-dbcp
            commons-dbcp
            1.2.2
        
        
        
            jstl
            jstl
            1.2
        
        
        
        
            log4j
            log4j
            ${log4j.version}
        


        
        
            com.alibaba
            fastjson
            1.1.41
        


        
            org.slf4j
            slf4j-api
            ${slf4j.version}
        

        
            org.slf4j
            slf4j-log4j12
            ${slf4j.version}
        
        
        
        
            org.codehaus.jackson
            jackson-mapper-asl
            1.9.13
        
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
            commons-io
            commons-io
            2.4
        
        
            commons-codec
            commons-codec
            1.9
        
        
            commons-lang
            commons-lang
            2.6
        
        
        com.fasterxml.jackson.core
        jackson-core
        2.1.0
    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.1.0
    
    
        com.fasterxml.jackson.core
        jackson-annotations
        2.1.0
        

    

    
        back-hotel
        
            
                maven-compiler-plugin
                
                    1.6
                    1.6
                
            
            
                maven-surefire-plugin
                
                    
                        **/*Tests.java
                    
                
            
        
    

2) 基础数据准备

CREATE TABLE `user_t` (  
  `id` INT(11) NOT NULL AUTO_INCREMENT,  
  `user_name` VARCHAR(40) NOT NULL,  
  `password` VARCHAR(255) NOT NULL,  
  `age` INT(4) NOT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=INNODB  DEFAULT CHARSET=utf8;  

/*Data for the table `user_t` */  

INSERT  INTO `user_t`(`id`,`user_name`,`password`,`age`) VALUES (1,'测试','sfasgfaf',24);

3) 项目结构(整体+细节)

整体目录结构如下:
Spring+SpringMVC+MyBatis详细整合过程_第1张图片

3.1 maven项目结构说明

src
  -main
      –bin 脚本库
      –java java源代码文件
      –resources 资源库,会自动复制到classes目录里
      –filters 资源过滤文件
      –assembly 组件的描述配置(如何打包)
      –config 配置文件
      –webapp web应用的目录。WEB-INF、css、js等
  -test
      –java 单元测试java源代码文件
      –resources 测试需要用的资源库
      –filters 测试资源过滤库
  -site Site(一些文档)
target
工程根目录下就只有src和target两个目录

target是有存放项目构建后的文件和目录,jar包、war包、编译的class文件等。

target这个文件夹包括内容都是maven构建的时候生成的

3.2 项目配置细节

Spring+SpringMVC+MyBatis详细整合过程_第2张图片

3.2.1 配置文件说明

Spring+SpringMVC+MyBatis详细整合过程_第3张图片

1)jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/user
username=root
password=123
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

数据库的基础配置

2)log4j.properties

#定义LOG输出级别
log4j.rootLogger=debug,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
#设置输出日志文件编码(可以控制乱码情况)
log4j.appender.File.encoding=UTF-8

3)spring-config.xml

"1.0" encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
                http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    
    "com.hotel.back"/>
    
    <import resource="spring-datasource.xml"/>

4)spring-datasource.xml
mybatis与spring的结合配置如下:

"1.0" encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    
    "classpath:jdbc.properties" ignore-unresolvable="true"/>

    
    "com.hotel.back" />

    "dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        
        <property name="initialSize" value="${initialSize}">property>
        
        <property name="maxActive" value="${maxActive}">property>
        
        <property name="maxIdle" value="${maxIdle}">property>
        
        <property name="minIdle" value="${minIdle}">property>
        
        <property name="maxWait" value="${maxWait}">property>
    bean>

    
    
    <bean id="sqlSessionFactory" name="sqlSessionFactory"  class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    

    
    r">
        " value="com.hotel.back.dao" />
        " value="sqlSessionFactory">
    


    
    r"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        " ref="dataSource" />
    

5)mybatis-config.xml
mybatis基础信息配置

"1.0" encoding="UTF-8"?>
"-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">


        "cacheEnabled" value="false"/>
        "mapUnderscoreToCamelCase" value="true"/>
        "useGeneratedKeys" value="true"/>
        "safeRowBoundsEnabled" value="false"/>
        "defaultExecutorType" value="REUSE"/>
        "defaultStatementTimeout" value="600"/>
    

    
        "User" type="com.hotel.back.model.User"/>
    
    
        "mapping/user.xml"/>

    

3.3 java代码展示

Spring+SpringMVC+MyBatis详细整合过程_第4张图片

1)基础java代码如下

model类:
User.java

/*
* Copyright (c) 2012 Qunar.com. All Rights Reserved.
*/
package com.hotel.back.model;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * @author lili.ai created on 2016 2016/9/27 14:49
 * @version $Id$
 */
public class User {
    int id;
    String userName;
    String password;
    int age;

    public int getId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}

dao类:
UserDao.java

package com.hotel.back.dao; /*
 * Copyright (c) 2012 Qunar.com. All Rights Reserved.
 */

import com.hotel.back.model.User;
import org.apache.ibatis.annotations.Param;


public interface UserDao {

    public User selectUserById(@Param("id")int id);
}

service类:
UserService.java

package com.hotel.back.service; /*
 * Copyright (c) 2012 Qunar.com. All Rights Reserved.
 */

import com.hotel.back.model.User;


public interface UserService {

    public User selectUserById(int id);
}

UserServiceImpl.java

/*
* Copyright (c) 2012 Qunar.com. All Rights Reserved.
*/
package com.hotel.back.service;

import com.hotel.back.dao.UserDao;
import com.hotel.back.model.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lili.ai created on 2016 2016/9/27 15:40
 * @version $Id$
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;
    @Override
    public User selectUserById(int id) {
        return  userDao.selectUserById(id);
    }

}

controller类
UserController.java

/*
* Copyright (c) 2012 Qunar.com. All Rights Reserved.
*/
package com.hotel.back.Controller;

import com.hotel.back.model.User;
import com.hotel.back.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author lili.ai created on 2016 2016/9/27 17:17
 * @version $Id$
 */
@Controller
@RequestMapping("/user")
public class UserController {
        @Resource
        private UserService userService;

        @RequestMapping("/showUser")
        public String toIndex(HttpServletRequest request,Model model){
            int userId = Integer.parseInt(request.getParameter("id"));
            User user = userService.selectUserById(userId);
            model.addAttribute("user", user);
            return "hello";
        }
}

3.4 配置mapping文件

如上述所示,sql准备好了,java对象也都OK了,接着就是发挥mybatis的魔力了,即数据库字段与java object的映射

在上述配置中没有提到resources->mapping->user.xml
文件如下:

Spring+SpringMVC+MyBatis详细整合过程_第5张图片

user.xml

"1.0" encoding="UTF-8" ?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"com.hotel.back.dao.UserDao">

    "field">
        id,
        user_name as userName,
        password as password,
        age as age

    
    

**注意:在resources->mybatis-config.xml文件中将上述user.xml文件引入,达到具体的mapper映射的目的(具体见上述mybatis-config.xml)。


        "mapping/user.xml"/>

4 spring+mybatis结合的测试

4.1

这里写图片描述
AppTests.java

package com.hotel.back;

import com.hotel.back.model.User;
import com.hotel.back.service.UserService;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;



import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@ContextConfiguration(locations = {"classpath:spring-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class AppTests {
    private static Logger logger = LoggerFactory.getLogger(AppTests.class);

    @Autowired
    UserService userService;

    @org.junit.Test
    public void testtest() {
        User user= userService.selectUserById(1);
        logger.info("用户:{}",user);
    }
}

写到这里运行代码,可看到控制台上输出如下:

[com.hotel.back.AppTests] - 用户:User[id=1,userName=测试,password=sfasgfaf,age=24]

即为成功!

5 spring+mybatis+spring mvc的结合

配置web文件,web目录结构如下:
Spring+SpringMVC+MyBatis详细整合过程_第6张图片
在本项目中,index.jsp为初始欢迎界面。
hello.jsp为用户查询界面
web.xml配置了spring-mvc的基础信息,加载顺序等
mvc-dispatcher-servlet.xml配置了url转发页面,转发配置等
具体代码如下:
web.xml

"1.0" encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
    Archetype Created Web Application
    
    
        contextConfigLocation
        classpath:spring-config.xml
    
    
    
        encodingFilter
        class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <async-supported>trueasync-supported>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>SpringMVCservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
        <async-supported>trueasync-supported>
    servlet>
    <servlet-mapping>
        <servlet-name>SpringMVCservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>
    <welcome-file-list>
        <welcome-file>/index.jspwelcome-file>
    welcome-file-list>

web-app>

mvc-dispatcher-servlet.xml

"1.0" encoding="UTF-8"?>
    "http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    "com.hotel.back" />
    
    "mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
            list>
        property>
    bean>
    
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> 
            list>
        property>
    bean>

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


    
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="defaultEncoding" value="utf-8" />
        
        <property name="maxUploadSize" value="10485760000" />
        
        <property name="maxInMemorySize" value="40960" />
    bean>

beans>

欢迎界面index.jsp

<%--
  Created by IntelliJ IDEA.
  User: lili.ai
  Date: 2016/9/27
  Time: 17:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    


hello world

用户展示界面hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
"-//W3C//DTD HTML 4.01 Transitional//EN">


    测试



${user.userName}

由此所有的配置文件以及代码写完,配置tomcat,运行项目,结果如下:
启动tomcat,运行结果如下:
Spring+SpringMVC+MyBatis详细整合过程_第7张图片
说明tomcat运行正常,整个项目配置基本不存在问题。
访问具体的url,返回结果如下:

http://localhost:8080/user/showUser?id=1
这里写图片描述

看到这个结果说明spring+mybatis+springMVC结合成功

你可能感兴趣的:(java)