MyBatisSSM框架——详细整合教程(Spring+SpringMVC+MyBatis)

硬件环境:

处理器:intel CORE i5 7th Gen

内存: 4G

硬盘:500G

软件条件:windows 10

开环境:

IDE:MyEclipse 2014

jdk:1.7

服务器:tomcat 7.0

框架版本:

spring4.0 + springMVC4.0 + MyBatis 3.2.6 + Maven

享有准备干活起始举行为止,开始上正题:

整合spring+mybatis

第一步:始建一个Maven
web项目,引入相应的jar包。

Maven
web项目教程:http://blog.csdn.net/zhshulin/article/details/37921705

第二步:Maven引入需要之JAR包

为有利于后边说的时光不待引入JAR包,我此直接让闹所有需要之JAR包,那都是骨干的JAR包,每个包的凡为何的且发注释,就不再多说了。

 pom.xml:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sion</groupId>
  <artifactId>SSM</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SSM Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <properties>  
        <!-- spring版本号 -->  
        <spring.version>4.0.2.RELEASE</spring.version>  
        <!-- mybatis版本号 -->  
        <mybatis.version>3.2.6</mybatis.version>  
        <!-- log4j日志文件管理包版本 -->  
        <slf4j.version>1.7.7</slf4j.version>  
        <log4j.version>1.2.17</log4j.version>  
    </properties>  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- spring核心包 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</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-oxm</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>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  

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

        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <!-- mybatis核心包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>${mybatis.version}</version>  
        </dependency>  
        <!-- mybatis/spring包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        <!-- 导入java ee jar 包 -->  
        <dependency>  
            <groupId>javax</groupId>  
            <artifactId>javaee-api</artifactId>  
            <version>7.0</version>  
        </dependency>  
        <!-- 导入Mysql数据库链接jar包 -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.30</version>  
        </dependency>  
        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->  
        <dependency>  
            <groupId>commons-dbcp</groupId>  
            <artifactId>commons-dbcp</artifactId>  
            <version>1.2.2</version>  
        </dependency>  
        <!-- JSTL标签类 -->  
        <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>com.alibaba</groupId>  
            <artifactId>fastjson</artifactId>  
            <version>1.1.41</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 -->  
        <!-- 映入JSON -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.13</version>  
        </dependency>  
        <!-- 上传组件包 -->  
        <dependency>  
            <groupId>commons-fileupload</groupId>  
            <artifactId>commons-fileupload</artifactId>  
            <version>1.3.1</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-io</groupId>  
            <artifactId>commons-io</artifactId>  
            <version>2.4</version>  
        </dependency>  
        <dependency>  
            <groupId>commons-codec</groupId>  
            <artifactId>commons-codec</artifactId>  
            <version>1.9</version>  
        </dependency>  
  </dependencies>
  <build>
    <finalName>SSM</finalName>
  </build>
</project>

老三步:建立JDBC属性文件

jdbc.properties(文件编码修改为utf-8)

#MySQL数据库驱动 
driver=com.mysql.jdbc.Driver
#数据库连接
url=jdbc:mysql://127.0.0.1:3306/student
#MySQL数据库用户名 
username=root
#MySQL数据库密码 
password=root  
#定义初始连接数  
initialSize=0  
#定义最大连接数  
maxActive=20  
#定义最大空闲  
maxIdle=20  
#定义最小空闲  
minIdle=1  
#定义最长等待时间  
maxWait=60000  

 

季步:建立spring-mybatis.xml配置文件

 这些文件就之所以来完成spring和mybatis的重组的。这之中也一直不小行安排,重要的就是是自动扫描,自动注入,配置数据库。注释也老详细,我们看看即使清楚了。

 

<?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: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">  
    <!-- 自动扫描 -->  
    <context:component-scan base-package="com.sion" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  

    <bean id="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>  

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:com/sion/ssm/mapping/*.xml"></property>  
    </bean>  

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

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  

</beans>  

 

 

 

MyBatis,第五步:Log4j**特性文件**

 

log4j.rootLogger=INFO,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  

 

第六步:**创制测试用表


 

CREATE TABLE `student` (
  `STU_ID` varchar(12) NOT NULL auto_increment COMMENT '学生编号',
  `STU_NAME` varchar(20) default NULL COMMENT '学生姓名',
  `STU_SEX` varchar(2) default NULL COMMENT '学生性别',
  `STU_AGE` int(10) default NULL COMMENT '学生年龄',
  `STU_CLASS` varchar(50) default NULL COMMENT '学生班级',
  `STU_ADDRESS` varchar(200) default NULL COMMENT '家庭地址',
  PRIMARY KEY  (`STU_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('201401122345', '张三', '男', '20', '软件工程1701', '北京市海淀区苏州街XXX号');
INSERT INTO `student` VALUES ('201401122125', '李四', '女', '21', '工商管理1601', '山东省济南市历下区XXX街道XXX号');
INSERT INTO `student` VALUES ('201301572389', '王武', '男', '23', '电子商务1402', '河北省石家庄市长安区XXX号');

 

第七步:利用MyBatis Generator自动创造代码

参照博文:http://www.cnblogs.com/klslb/p/6908535.html

利用MyBatis
Generator创设的公文代码,已经拿增删改查的道漫天实现。不用还自己写,再一次证实一下,各样艺术的来意:

selectByPrimaryKey:冲主键ID查询单个对象【即便查询所有,将主键ID传入一个空字符串即可,记得代码要避空指针万分】

deleteByPrimaryKey:基于主键ID删除单个对象

insert:插入新数据(插入所有数据项)

insertSelective:栽新数据(插入N个数据项【N小于等于表字段数量】)

updateByPrimaryKeySelective:冲主键ID修改单个对象的数额(修改N个数据项【N小于等于表字段数量】)

updateByPrimaryKey:遵照主键ID修改单个对象的数量(修改所暴发数据)

 

树立项目目录结构,将创好之实体类,映射文件,dao代码,放到相应的包下。

留神:记得改映射文件的

<mapper
namespace=”DAO接口全路线” >
<resultMap id=”BaseResultMap” type=”对应实体类都路线” >

<insert
id=”insert” parameterType=”对应实体类都路线” >

<insert
id=”insertSelective” parameterType=”对应实体类都路线” >

<update
id=”updateByPrimaryKeySelective” parameterType=”对应实体类都路线”
>

<update
id=”updateByPrimaryKey” parameterType=”对应实体类都路线” >

 

第八步:建立工作类似接口及贯彻类似

以工作包下新建一个接口IStudentService和Student瑟维斯(Service)(Service)Impl

 

IStudentService代码:

 

package com.sion.ssm.service;

import com.sion.ssm.po.Student;

public interface IStudentService {
    int deleteByPrimaryKey(Integer stuId);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer stuId);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

 

 

 

StudentServiceImpl代码:

 

 

 StudentServiceImpl实现IStudentService(Service)重写里面所有的不二法门后,注入DAO,然后相应的形式调用DAO相应的情势即可,因为是单表查询,没有什么业务逻辑处理,所以一贯调用,假使项目遭到干到事情处理,可以当StudentServiceImpl相应的法门中描绘代码做作业处理,因为Service我便是做事情逻辑处理的。

 

package com.sion.ssm.service.impl;

import org.springframework.stereotype.Service;

import com.sion.ssm.dao.IStudentDAO;
import com.sion.ssm.po.Student;
import com.sion.ssm.service.IStudentService;
@Service("studentService") 
public class StudentServiceImpl implements IStudentService{
    /* 注入DAO */
    private IStudentDAO studentDAO;

    @Override
    public int deleteByPrimaryKey(Integer stuId) {
        return this.studentDAO.deleteByPrimaryKey(stuId);
    }

    @Override
    public int insert(Student student) {
        return this.studentDAO.insert(student);
    }

    @Override
    public int insertSelective(Student student) {
        return this.studentDAO.insertSelective(student);
    }

    @Override
    public Student selectByPrimaryKey(Integer student) {
        return this.studentDAO.selectByPrimaryKey(student);
    }

    @Override
    public int updateByPrimaryKeySelective(Student student) {
        return this.studentDAO.updateByPrimaryKeySelective(student);
    }

    @Override
    public int updateByPrimaryKey(Student student) {
        return this.studentDAO.updateByPrimaryKey(student);
    }

}

至那!已经完结了spring+mybatis的构成,接下去继续拓展springMVC的组成!

 

整合SpringMVC

 

 第一步:配置spring-mvc.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: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">  
    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->  
   <context:component-scan base-package="com.sion.ssm.action" />  
   <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  
   <bean id="mappingJacksonHttpMessageConverter"  
       class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
       <property name="supportedMediaTypes">  
           <list>  
               <value>text/html;charset=UTF-8</value>  
           </list>  
       </property>  
   </bean>  
   <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->  
   <bean  
       class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
       <property name="messageConverters">  
           <list>  
               <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->  
           </list>  
       </property>  
   </bean>  
   <!-- 定义跳转的文件的前后缀 ,视图模式配置-->  
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
       <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->  
       <property name="prefix" value="/WEB-INF/jsp/" />  
       <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>  

第二步:配置web.xml文件

这里对spring-mybatis.xml的引入和部署的spring-mvc的Servlet就是为好SSM整合,从前2框架整合不欲在此间举行其他配置。配置一样来详尽阐明,不多说了。

<!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>
  <!-- Spring和mybatis的配置文件 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:spring-mybatis.xml</param-value>  
    </context-param>  
    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
    <!-- Spring监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring内存溢出监听器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  

    <!-- Spring MVC servlet -->  
    <servlet>  
        <servlet-name>SpringMVC</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:spring-MVC.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>SpringMVC</servlet-name>  
        <!-- 此处可以可以配置成*.do  *.action,对应struts的后缀习惯 -->  
        <url-pattern>*.action</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>/index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>

至这停止,基本上ssm整合已好!可以把品种布局到tomcat下运作,访问localhost:8080/SSM,假诺出现以下界面,表达,恭喜您!大功告成!

MyBatis 1

 

网站地图xml地图