zoukankan      html  css  js  c++  java
  • 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)

    整合Spring和Mybatis

    首先给出完整的项目目录:

    (1)引入项目需要的jar包

    使用http://maven.apache.org作为中央仓库即可。
    Spring核心包,mybatis核心包,json数据需要的包【经常需要用到】,log4j日志管理包。

    <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>springDemo</groupId>
      <artifactId>springDemo</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>
      <name>springDemo</name>
      <url>http://maven.apache.org</url>
      
      <description>搭建Spring+SpringMVC+mybatis开发环境</description>
      
      <properties>
    	  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    	  <!-- spring版本号 -->  
    	  <spring.version>3.2.4.RELEASE</spring.version>  
    	  <org.aspectj.version>1.7.3</org.aspectj.version>  
    	  <!-- mybatis版本号 -->  
    	  <mybatis.version>3.2.4</mybatis.version>  
    	  <!-- log4j日志文件管理包版本 -->  
    	  <slf4j.version>1.6.6</slf4j.version>  
    	  <log4j.version>1.2.12</log4j.version>  
      </properties>
      
      <dependencies>  
           <!-- spring核心包 -->  
           <!-- springframe start -->  
           <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>  
     
           <dependency>  
               <groupId>org.aspectj</groupId>  
               <artifactId>aspectjweaver</artifactId>  
               <version>${org.aspectj.version}</version>  
           </dependency>  
           <dependency>  
               <groupId>org.aspectj</groupId>  
               <artifactId>aspectjrt</artifactId>  
               <version>${org.aspectj.version}</version>  
           </dependency>  
     
           <dependency>  
               <groupId>cglib</groupId>  
               <artifactId>cglib</artifactId>  
               <version>2.2.2</version>  
           </dependency>  
           <dependency>  
               <groupId>cglib</groupId>  
               <artifactId>cglib-nodep</artifactId>  
               <version>2.2.2</version>  
           </dependency>  
           <!-- springframe end -->  
     
           <!-- 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>  
           <!-- mysql驱动包 -->  
           <dependency>  
               <groupId>mysql</groupId>  
               <artifactId>mysql-connector-java</artifactId>  
               <version>5.1.29</version>  
           </dependency>  
           <!-- junit测试包 -->  
           <dependency>  
               <groupId>junit</groupId>  
               <artifactId>junit</artifactId>  
               <version>4.11</version>  
               <scope>test</scope>  
           </dependency>  
           <!-- 阿里巴巴数据源包 -->  
           <dependency>  
               <groupId>com.alibaba</groupId>  
               <artifactId>druid</artifactId>  
               <version>1.0.2</version>  
           </dependency>  
     
           <dependency>  
               <groupId>org.apache.commons</groupId>  
               <artifactId>commons-lang3</artifactId>  
               <version>3.1</version>  
           </dependency>  
     
           <dependency>  
               <groupId>commons-dbcp</groupId>  
               <artifactId>commons-dbcp</artifactId>  
               <version>1.4</version>  
           </dependency>  
     
           <!-- json数据 -->  
           <dependency>  
               <groupId>org.codehaus.jackson</groupId>  
               <artifactId>jackson-mapper-asl</artifactId>  
               <version>1.9.13</version>  
           </dependency>  
     
           <dependency>  
               <groupId>commons-lang</groupId>  
               <artifactId>commons-lang</artifactId>  
               <version>2.6</version>  
           </dependency>  
     
           <dependency>  
               <groupId>javax.servlet</groupId>  
               <artifactId>jstl</artifactId>  
               <version>1.2</version>  
           </dependency>  
           <dependency>  
               <groupId>javax.servlet</groupId>  
               <artifactId>servlet-api</artifactId>  
               <version>2.5</version>  
           </dependency>  
     
           <dependency>  
               <groupId>org.apache.velocity</groupId>  
               <artifactId>velocity</artifactId>  
               <version>1.7</version>  
           </dependency>  
           <dependency>  
               <groupId>org.apache.velocity</groupId>  
               <artifactId>velocity-tools</artifactId>  
               <version>2.0</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 -->  
       </dependencies>
      
      <build>
        <plugins>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
              <version>3.0</version>
              <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </project>
    

    (2)配置spring-mybatis.xml文件

    该文件是为了整合spring和mybatis。
    由于mybatis需要用到数据库的配置,创建jdbc.properties

    jdbc_driverClassName=com.mysql.jdbc.Driver
    jdbc_url=jdbc:mysql://localhost:3306/weixin?useUnicode=true&amp;characterEncoding=utf-8
    jdbc_username=root
    jdbc_password=
    #定义初始连接数
    initialSize=0
    #定义最大连接数
    maxActive=20
    #定义最大空闲
    maxIdle=20
    #定义最小空闲
    minIdle=1
    #定义最长等待时间
    maxWait=60000
    

    现在开始配置spring-mybatis.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">
        <!-- 自动扫描 -->
        <context:component-scan base-package="com.aheizi" />
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:properties/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/aheizi/mapping/*.xml"></property>
        </bean>
     
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.aheizi.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>
    

    这里我们已经完成了spring和mybatis的整合。下面配置log4j和JUnit:

    (3)Log4j的配置

    Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接字的服务器,NT的事件记录器、UNIX Syslog守护进程等;我们可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致的控制日志的生成过程。
    Log4J的配置是通用的,下面给出基本配置。

    #定义LOG输出级别
    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
    

    (4)JUnit测试

    下面写一个根据ID查询User的简单测试。
    创建user表:

    DROP TABLE IF EXISTS `user_t`;
     
    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 AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
     
    /*Data for the table `user_t` */
     
    insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'测试','sfasgfaf',24);
    

    创建实体类,Mybatis映射文件,以及DAO接口。(注:也可以使用MyBatis Generator自动创建代码,详情见http://blog.csdn.net/zhshulin/article/details/23912615)
    User类:

    package com.aheizi.domain;
    public class User {
        private Integer id;
        private String userName;
        private String password;
        private Integer age;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName == null ? null : userName.trim();
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    

    UserMaper.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.aheizi.dao.UserMapper" >
      <resultMap id="BaseResultMap" type="com.aheizi.domain.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
      </resultMap>
      
      <sql id="Base_Column_List" >
        id, user_name, password, age
      </sql>
      
      <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from user_t
        where id = #{id,jdbcType=INTEGER}
      </select>
      
    </mapper>
    

    UserMapper接口

    package com.aheizi.Dao;
    import com.aheizi.domain.User;
    public interface UserMapper {
        int deleteByPrimaryKey(Integer id);
        int insert(User record);
        int insertSelective(User record);
        User selectByPrimaryKey(Integer id);
        int updateByPrimaryKeySelective(User record);
        int updateByPrimaryKey(User record);
    }
    

    service接口和实现类

    接口UserService

    package com.aheizi.service;
    import com.aheizi.domain.User;
    public interface UserService {
    	
    	public User getUserById(int userId);
    	
    }
    

    实现类UserServiceImpl

    package com.aheizi.service.impl;
    import javax.annotation.Resource;
    import org.springframework.stereotype.Service;
    import com.aheizi.dao.UserMapper;
    import com.aheizi.domain.User;
    import com.aheizi.service.UserService;
    @Service("userService")
    public class UserServiceImpl implements UserService {
    	
    	@Resource
    	private UserMapper userDao;
    	
    	@Override
    	public User getUserById(int userId) {
    		// TODO Auto-generated method stub
    		return userDao.selectByUserId(userId);
    	}
    }
    

    建立测试类
    测试类在src/test/java中建立。如果测试成功,表示Spring和Mybatis已经整合成功了。输出信息使用的是Log4j打印到控制台。

    这里maven install的时候,可能会报错。
    1.详见maven项目编译漏掉src/main/java下的xml配置文件
    2.log4j的配置文件log4j.properties文件暂时需要先放在resource根目录下,默认的加载目录就是根目录。
    等整合springMVC的时候可以在web.xml配置log4jConfigLocation来指定目录。

    不使用spring,直接测试mybatis:

    package com.aheizi.testmybatis;
    import javax.annotation.Resource;
    import org.apache.log4j.Logger;
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import com.aheizi.domain.User;
    import com.aheizi.service.UserService;
    public class TestMybatis {
    private static Logger logger = Logger.getLogger(TestSpringDemo.class);
    	
    	private ApplicationContext ac = null;
    	
        @Resource
        private UserService userService = null;
        
    	@Before
    	public void before() {
    	    ac = new ClassPathXmlApplicationContext("config/spring-mybatis.xml");
    	    userService = (UserService) ac.getBean("userService");
    	}
     
        @Test
        public void test1() {
            User user = userService.getUserById(1);
            logger.info("userName" + user.getUserName());
        }
    }
    

    测试输出:

    [org.springframework.context.support.ClassPathXmlApplicationContext] - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@51de0b09: startup date [Tue Sep 01 18:06:48 CST 2015]; root of context hierarchy
    [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from class path resource [config/spring-mybatis.xml]
    [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [properties/jdbc.properties]
    [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@524decad: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy
    [com.aheizi.testmybatis.TestSpringDemo] - userName测试
    

    使用Spring,使用了Spring那么就可以使用注解的方式来引入配置文件和类,然后再将service接口对象注入。

    package com.aheizi.testmybatis;
    
    import javax.annotation.Resource;
    
    import org.apache.log4j.Logger;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.aheizi.domain.User;
    import com.aheizi.service.UserService;
    
    @RunWith(SpringJUnit4ClassRunner.class)     //表示继承了SpringJUnit4ClassRunner类
    @ContextConfiguration(locations = {"classpath*:config/spring-mybatis.xml"})
    public class TestSpringDemo {
    	private static Logger logger = Logger.getLogger(TestSpringDemo.class);
    	
        @Resource
        private UserService userService = null;
        
        @Test
        public void test1() {
            User user = userService.getUserById(1);
            logger.info("userName" + user.getUserName());
        }
    	
    }
    
    

    测试输出:

    [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from URL [file:/D:/workspace/springDemo/target/classes/config/spring-mybatis.xml]
    [org.springframework.context.support.GenericApplicationContext] - Refreshing org.springframework.context.support.GenericApplicationContext@58d7330d: startup date [Tue Sep 01 18:15:56 CST 2015]; root of context hierarchy
    [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer] - Loading properties file from class path resource [properties/jdbc.properties]
    [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6a9b65cc: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy
    [com.aheizi.testmybatis.TestSpringDemo] - userName测试
    [org.springframework.context.support.GenericApplicationContext] - Closing org.springframework.context.support.GenericApplicationContext@58d7330d: startup date [Tue Sep 01 18:15:56 CST 2015]; root of context hierarchy
    [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6a9b65cc: defining beans [userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,propertyConfigurer,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,transactionManager,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy
    

    并且这两种测试的时候会伴随着日志文件的输出。

    源码下载地址:源码

  • 相关阅读:
    052 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 14 Eclipse下程序调试——debug2 多断点调试程序
    051 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 13 Eclipse下程序调试——debug入门1
    050 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 12 continue语句
    049 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 11 break语句
    048 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 10 案例——阶乘的累加和
    047 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 09 嵌套while循环应用
    046 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 08 for循环的注意事项
    045 01 Android 零基础入门 01 Java基础语法 05 Java流程控制之循环结构 07 for循环应用及局部变量作用范围
    剑指OFFER----面试题04.二维数组中的查找
    剑指OFFER----面试题03. 数组中重复的数字
  • 原文地址:https://www.cnblogs.com/aheizi/p/4782042.html
Copyright © 2011-2022 走看看