MyBatis学习总计(八)——Mybatis3.x与Spring4.x整合

一、搭建开发环境

1.1、使用Maven创建Web项目

  执行如下命令:

mvn archetype:create -DgroupId=me.gacl -DartifactId=spring4-mybatis3 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

 如下图所示:
  图片 1

  创造好的门类如下:

  图片 2

  编辑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>me.gacl</groupId>
  <artifactId>spring4-mybatis3</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring4-mybatis3 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>spring4-mybatis3</finalName>
  </build>
</project>

 修改 <name>spring4-mybatis3 Maven Webapp</name> 部分,把” Maven
Webapp”那部分带有空格的情节去掉,否则Maven在编译项目时会因为空格的缘故导致有的半间半界的错误出现,修改成: <name>spring4-mybatis3</name> 。

  此外,把以下内容删掉:

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
</dependency>

 那有些是junit的jar包依赖音信,这一个版本太低了,我们不接纳那个Junit测试版本,修改过后的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>me.gacl</groupId>
  <artifactId>spring4-mybatis3</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>spring4-mybatis3</name>
  <url>http://maven.apache.org</url>
  <dependencies>

  </dependencies>
  <build>
    <finalName>spring4-mybatis3</finalName>
  </build>
</project>

 

1.二,将创制好的花色导入MyEclipse中

  具体操作步骤如下图所示:

  图片 3

  图片 4

  图片 5

  图片 6

  图片 7

  手动创设【src/main/java】、【src/test/resources】、【src/test/java】这三个source
folder,如下图所示:

  图片 8

  到此,项目搭建的办事就是是一体形成了。

二、创设数据库和表(针对MySQL)

SQL脚本如下:

Create DATABASE spring4_mybatis3;
USE spring4_mybatis3;

DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user (
  user_id char(32) NOT NULL,
  user_name varchar(30) DEFAULT NULL,
  user_birthday date DEFAULT NULL,
  user_salary double DEFAULT NULL,
  PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 成立好的数据库和表如下:

  图片 9

三、使用generator工具生成代码

  在网上找到了1个generator工具得以依照创造好的数据库表生成MyBatis的表对应的实体类,SQL映射文件和dao,找到generator工具根目录下的generator.xml文件,那么些文件是用来布署代码生成规则的,如下图所示:

  图片 10

  编辑generator.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动包位置 -->
    <classPathEntry location="E:\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar" /> 
    <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库链接URL、用户名、密码 -->
         <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/spring4_mybatis3" userId="root" password="XDP"> 
        <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成实体类的包名和位置,这里配置将生成的实体类放在me.gacl.domain这个包下 -->
        <javaModelGenerator targetPackage="me.gacl.domain" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的SQL映射文件包名和位置,这里配置将生成的SQL映射文件放在me.gacl.mapping这个包下 -->
        <sqlMapGenerator targetPackage="me.gacl.mapping" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置,这里配置将生成的dao类放在me.gacl.dao这个包下 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="me.gacl.dao" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>

 打开命令行窗口,切换来变化工具的根目录下,执行如下命令:

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

 如下图所示:
  图片 11

  刚才大家在generator.xml文件中布局将转变的代码和SQL映射文件放到”C:\Users\gacl\spring4-mybatis3\src\main\java”这几个目录下,那几个目录就是我们的spring4-mybatis3品种所在目录,大家刷新一下src/main/java目录,就可以看出变化的代码和照耀文件了,如下图所示:

  图片 12

  生成的代码和照耀文件一行都无须改,可以间接行使到花色当中。上边我们看一眼由generator工具生成的代码和照耀文件:

  1、生成的dao类

package me.gacl.dao;

import me.gacl.domain.User;

public interface UserMapper {
    int deleteByPrimaryKey(String userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(String userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

 生成的UserMapper是贰个接口,里面定义了部分操作t_user表的增删改查方法。

2、生成的实体类

package me.gacl.domain;

import java.util.Date;

public class User {
    private String userId;

    private String userName;

    private Date userBirthday;

    private Double userSalary;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public Date getUserBirthday() {
        return userBirthday;
    }

    public void setUserBirthday(Date userBirthday) {
        this.userBirthday = userBirthday;
    }

    public Double getUserSalary() {
        return userSalary;
    }

    public void setUserSalary(Double userSalary) {
        this.userSalary = userSalary;
    }
}

 User类是t_user表的对应的实体类,User类中定义的性质和t_user表中的字段一一对应。

  叁,生成的SQL映射文件

<?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="me.gacl.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="me.gacl.domain.User" >
    <id column="user_id" property="userId" jdbcType="CHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_birthday" property="userBirthday" jdbcType="DATE" />
    <result column="user_salary" property="userSalary" jdbcType="DOUBLE" />
  </resultMap>
  <sql id="Base_Column_List" >
    user_id, user_name, user_birthday, user_salary
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where user_id = #{userId,jdbcType=CHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_user
    where user_id = #{userId,jdbcType=CHAR}
  </delete>
  <insert id="insert" parameterType="me.gacl.domain.User" >
    insert into t_user (user_id, user_name, user_birthday, 
      user_salary)
    values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, 
      #{userSalary,jdbcType=DOUBLE})
  </insert>
  <insert id="insertSelective" parameterType="me.gacl.domain.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        user_id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userBirthday != null" >
        user_birthday,
      </if>
      <if test="userSalary != null" >
        user_salary,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        #{userId,jdbcType=CHAR},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        #{userBirthday,jdbcType=DATE},
      </if>
      <if test="userSalary != null" >
        #{userSalary,jdbcType=DOUBLE},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="me.gacl.domain.User" >
    update t_user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        user_birthday = #{userBirthday,jdbcType=DATE},
      </if>
      <if test="userSalary != null" >
        user_salary = #{userSalary,jdbcType=DOUBLE},
      </if>
    </set>
    where user_id = #{userId,jdbcType=CHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="me.gacl.domain.User" >
    update t_user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_birthday = #{userBirthday,jdbcType=DATE},
      user_salary = #{userSalary,jdbcType=DOUBLE}
    where user_id = #{userId,jdbcType=CHAR}
  </update>
</mapper>

 UserMapper.xml这么些文件的故事情节是编写操作t_user表的SQL语句,重点说一下UserMapper.xml配置中须要注意的多少个小细节难点:

  1、UserMapper.xml的<mapper>标签的namespace必须是UserMapper接口的全类名,既<mapper namespace=”me.gacl.dao.UserMapper”
>

  二,UserMapper.xml的定义操作数据库的<select><delete><update><insert>这么些标签的id属性的值必须和UserMapper接口定义的格局名相同,如下图所示:

  图片 13

  之所以有上述说的那两点须求,就是为着可以让MyBatis可以基于UserMapper接口和UserMapper.xml文件去自动已毕UserMapper接口中定义的连带措施,那样咱们就不再要求针对UserMapper接口去编写具体的落成代码了。

四、Spring与MyBatis整合

  首先大家要在类型中加入大家要求的相关jar包,我们可以到Maven的中心仓库:http://search.maven.org/ 找到我们要的连锁jar包,如下图所示:

  图片 14

  大家只要求在摸索框中输入要找的jar包的称谓,点击【SEA昂科威CH】按钮,就可以找到大家要的jar包了。

4.1、添加Spring与Mybatis的相关jar包

  壹,添加spring-core,输入spring-core关键字展开查找,如下图所示:

  图片 15

  找到关于spring-core的保护描述信息,如下图所示:

  图片 16

  将

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.1.4.RELEASE</version>
</dependency>

 复制到花色的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>me.gacl</groupId>
    <artifactId>spring4-mybatis3</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring4-mybatis3</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- 添加Spring4.1.4的核心包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>spring4-mybatis3</finalName>
    </build>
</project>

 那样Maven就会自动帮大家从Maven的焦点仓库中下载spring-core这些jar包到大家的地头仓库,然后将spring-core那一个jar包以及它的有关着重包参加到大家的花色当中,如下所示:

  图片 17

  spring4.x与mybatis3.x所必要的连带jar包都得以选取上述所说的主意展开搜索,然后添加到项目当中,添加完spring4.x与mybatis3.x相关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>me.gacl</groupId>
    <artifactId>spring4-mybatis3</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring4-mybatis3</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- 添加Spring-core包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!-- 添加spring-context包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!-- 添加spring-tx包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!-- 添加spring-jdbc包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!-- 为了方便进行单元测试,添加spring-test包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!--添加spring-web包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>
        <!--添加aspectjweaver包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>
        <!-- 添加mybatis的核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.8</version>
        </dependency>
        <!-- 添加mybatis与Spring整合的核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- 添加servlet3.0核心包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.2-b01</version>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 添加mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <!-- 添加druid连接池包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.12</version>
        </dependency>
        <!-- 添加junit单元测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring4-mybatis3</finalName>
    </build>
</project>

 图片 18

4.二,编写相关安顿文件

  1、dbconfig.properties

  在src/main/resources目录下创办一个dbconfig.properties文件,用于编写连接MySQL数据库的连锁新闻,dbconfig.properties的内容如下:

driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=XDP

 2、spring.xml(spring框架的配置文件)

  在src/main/resources目录下创制2个spring.xml文件,spring.xml文件就是对准Spring框架编写的主旨配置文件,spring.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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 引入dbconfig.properties属性文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!-- 自动扫描(自动注入),扫描me.gacl.service这个包以及它的子包的所有使用@Service注解标注的类 -->
    <context:component-scan base-package="me.gacl.service" />
</beans>

   我们的spring.xml文件的配备非凡简单,就七个布局。
  3、spring-mybatis.xml(spring与mybatis整合的布署文件)

  在src/main/resources目录下创设七个spring-mybatis.xml文件,spring-mybatis.xml文件就是针对性Spring框架与Mybatis框架整合编写的布局文件,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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

    <!-- JNDI方式配置数据源 -->
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
    <!-- ========================================配置数据源========================================= -->
    <!-- 配置数据源,使用的是alibaba的Druid(德鲁伊)数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <!-- 
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> 
        -->
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- ========================================分隔线========================================= -->

    <!-- ========================================针对myBatis的配置项============================== -->
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置
        value="classpath:me/gacl/mapping/*.xml"指的是classpath(类路径)下me.gacl.mapping包中的所有xml文件
        UserMapper.xml位于me.gacl.mapping包下,这样UserMapper.xml就可以被自动扫描
         -->
        <property name="mapperLocations" value="classpath:me/gacl/mapping/*.xml" />
    </bean>
    <!-- 配置扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描me.gacl.dao这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="me.gacl.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- ========================================分隔线========================================= -->
    <!-- 配置Spring的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 注解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* me.gacl.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


    <!-- 配置druid监控spring jdbc -->
    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>me.gacl.service.*</value>
            </list>
        </property>
    </bean>
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>

</beans>

 到此,相关的布署文件到底编写成功了,如下图所示:

  图片 19

4.三,举办单元测试

  经过以上多个步骤,spring4与mybatis3的三结合算是全部完毕了。接下来大家要做的工作就是进行单元测试,测试一下spring4与mybatis3的构成是还是不是成功。

  一,在src/main/java目录下开创贰个me.gacl.service包,然后在me.gacl.service包成立三个UserServiceI接口,如下所示:

package me.gacl.service;

import me.gacl.domain.User;

public interface UserServiceI {

    /**
     * 添加用户
     * @param user
     */
    void addUser(User user);

    /**
     * 根据用户id获取用户
     * @param userId
     * @return
     */
    User getUserById(String userId);
}

 2、在src/main/java目录下创设3个me.gacl.service.impl包,然后在me.gacl.service.impl包创造三个针对UserServiceI接口的兑现类:UserServiceImpl,如下所示:

package me.gacl.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import me.gacl.dao.UserMapper;
import me.gacl.domain.User;
import me.gacl.service.UserServiceI;

/**
 * @author gacl
 * 使用@Service注解将UserServiceImpl类标注为一个service
 * service的id是userService
 */
@Service("userService")
public class UserServiceImpl implements UserServiceI {

    /**
     * 使用@Autowired注解标注userMapper变量,
     * 当需要使用UserMapper时,Spring就会自动注入UserMapper
     */
    @Autowired
    private UserMapper userMapper;//注入dao

    @Override
    public void addUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public User getUserById(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}

 创造好的五个类如下所示:

  图片 20

  叁,在src/test/java目录下编制单元测试类,新建一个me.gacl.test包,然后在那些包下创建一个MyBatisTest类,代码如下:

package me.gacl.test;

import java.util.Date;
import java.util.UUID;
import me.gacl.domain.User;
import me.gacl.service.UserServiceI;
//import me.gacl.service.UserServiceI;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyBatisTest {

    private UserServiceI userService;

    /**
     * 这个before方法在所有的测试方法之前执行,并且只执行一次
     * 所有做Junit单元测试时一些初始化工作可以在这个方法里面进行
     * 比如在before方法里面初始化ApplicationContext和userService
     */
    @Before
    public void before(){
        //使用"spring.xml"和"spring-mybatis.xml"这两个配置文件创建Spring上下文
        ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
        //从Spring容器中根据bean的id取出我们要使用的userService对象
        userService = (UserServiceI) ac.getBean("userService");
    }

    @Test
    public void testAddUser(){
        //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});
        //UserServiceI userService = (UserServiceI) ac.getBean("userService");
        User user = new User();
        user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setUserName("白虎神皇xdp");
        user.setUserBirthday(new Date());
        user.setUserSalary(10000D);
        userService.addUser(user);
    }

}

 执行单元测试代码,那时候会报如下错误:

   图片 21

  错误提醒是说没有找到”me.gacl.test.MyBatisTest”那些类,那是因为我们并未运用maven编译项目中的类的因由。

  上面大家应用Maven编译项目,选中项目标pom.xml文件→【Debug
As】→【maven install】,如下所示:

  图片 22

编译结果如下:

  图片 23

  在此间说一下我执行Maven install之后遇到的题材,第三回实践Maven
install命令时,就涌出了如下一堆一无可取的不当:

  图片 24

  后来自家把项目删掉,再另行导入项目,然后再履行Clean项目操作之后,如下图所示:

  图片 25

  再履行Maven
install操作又有啥不可平常编译通过了,那让小编郁闷了绵绵,那应当不是本人项目配置的由来,而是Maven的来头,具体也不知情干什么会如此。反正这毕竟一种消除办法吧,比方遇上执行Maven
install操作不能符合规律编译通过的情况:可以尝尝接纳:Maven
clean→Clean项目→Maven install那三个步骤去消除难题

  除了可以用健康的Junit进行单元测试之外,大家还足以选取Spring提供的Junit测试框架进行单元测试,在me.gacl.test下新建三个MyBatisTestBySpringTestFramework类,代码如下:

package me.gacl.test;

import java.util.Date;
import java.util.UUID;
import me.gacl.domain.User;
import me.gacl.service.UserServiceI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
//配置了@ContextConfiguration注解并使用该注解的locations属性指明spring和配置文件之后,
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml" })
public class MyBatisTestBySpringTestFramework {

    //注入userService
    @Autowired
    private UserServiceI userService;

    @Test
    public void testAddUser(){
        User user = new User();
        user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setUserName("xdp_gacl_白虎神皇");
        user.setUserBirthday(new Date());
        user.setUserSalary(10000D);
        userService.addUser(user);
    }

    @Test
    public void testGetUserById(){
        String userId = "fb1c5941094e400b975f10d9a9d602a3";
        User user = userService.getUserById(userId);
        System.out.println(user.getUserName());
    }
}

 执行那多少个测试方法,是足以健康测试通过的,如下所示:

  图片 26
  图片 27

  到此,大家框架的构成测试工作就是是整个通过了,整合成功。

4.肆,在web服务器中展开测试

  一,编辑web.xml文件,添加spring监听器配置项,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <description>Spring监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- ContextLoaderListener初始化Spring上下文时需要使用到的contextConfigLocation参数 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 配置spring.xml和spring-mybatis.xml这两个配置文件的位置,固定写法 -->
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
    </context-param>
</web-app>

 二,在UserMapper接口中添加多个获取具有用户音信的getAllUser()方法,如下所示:

package me.gacl.dao;

import java.util.List;

import me.gacl.domain.User;

public interface UserMapper {
    int deleteByPrimaryKey(String userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(String userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    /**获取所有用户信息
     * @return List<User>
     */
    List<User> getAllUser();
}

 3、在UserMapper.xml文件中编辑getAllUser()方法要实践的SQL语句,如下所示:

<?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="me.gacl.dao.UserMapper" >
  <resultMap id="BaseResultMap" type="me.gacl.domain.User" >
    <id column="user_id" property="userId" jdbcType="CHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_birthday" property="userBirthday" jdbcType="DATE" />
    <result column="user_salary" property="userSalary" jdbcType="DOUBLE" />
  </resultMap>
  <sql id="Base_Column_List" >
    user_id, user_name, user_birthday, user_salary
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_user
    where user_id = #{userId,jdbcType=CHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_user
    where user_id = #{userId,jdbcType=CHAR}
  </delete>
  <insert id="insert" parameterType="me.gacl.domain.User" >
    insert into t_user (user_id, user_name, user_birthday, 
      user_salary)
    values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, 
      #{userSalary,jdbcType=DOUBLE})
  </insert>
  <insert id="insertSelective" parameterType="me.gacl.domain.User" >
    insert into t_user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        user_id,
      </if>
      <if test="userName != null" >
        user_name,
      </if>
      <if test="userBirthday != null" >
        user_birthday,
      </if>
      <if test="userSalary != null" >
        user_salary,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="userId != null" >
        #{userId,jdbcType=CHAR},
      </if>
      <if test="userName != null" >
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        #{userBirthday,jdbcType=DATE},
      </if>
      <if test="userSalary != null" >
        #{userSalary,jdbcType=DOUBLE},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="me.gacl.domain.User" >
    update t_user
    <set >
      <if test="userName != null" >
        user_name = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="userBirthday != null" >
        user_birthday = #{userBirthday,jdbcType=DATE},
      </if>
      <if test="userSalary != null" >
        user_salary = #{userSalary,jdbcType=DOUBLE},
      </if>
    </set>
    where user_id = #{userId,jdbcType=CHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="me.gacl.domain.User" >
    update t_user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_birthday = #{userBirthday,jdbcType=DATE},
      user_salary = #{userSalary,jdbcType=DOUBLE}
    where user_id = #{userId,jdbcType=CHAR}
  </update>

  <!-- ==============以下内容是根据自身业务扩展的内容======================= -->
      <!-- select标签的id属性与UserMapper接口中定义的getAllUser方法要一模一样 -->
    <select id="getAllUser" resultMap="BaseResultMap">
        select user_id, user_name, user_birthday, user_salary from t_user
    </select>
</mapper>

 肆,在UserServiceI接口中也丰盛壹个getAllUser()方法,如下:

package me.gacl.service;

import java.util.List;

import me.gacl.domain.User;

public interface UserServiceI {

    /**
     * 添加用户
     * @param user
     */
    void addUser(User user);

    /**
     * 根据用户id获取用户
     * @param userId
     * @return
     */
    User getUserById(String userId);

    /**获取所有用户信息
     * @return List<User>
     */
    List<User> getAllUser();
}

 5、在User瑟维斯Impl类中达成getAllUser方法,如下:

package me.gacl.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import me.gacl.dao.UserMapper;
import me.gacl.domain.User;
import me.gacl.service.UserServiceI;

/**
 * @author gacl
 * 使用@Service注解将UserServiceImpl类标注为一个service
 * service的id是userService
 */
@Service("userService")
public class UserServiceImpl implements UserServiceI {

    /**
     * 使用@Autowired注解标注userMapper变量,
     * 当需要使用UserMapper时,Spring就会自动注入UserMapper
     */
    @Autowired
    private UserMapper userMapper;//注入dao

    @Override
    public void addUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public User getUserById(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
}

 陆,在src/main/java目录下开创三个me.gacl.web.controller包,然后在me.gacl.web.controller下创制2个UserServlet,如下:

package me.gacl.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import me.gacl.domain.User;
import me.gacl.service.UserServiceI;

/**
 * @author gacl
 * @WebServlet是Servlet3.0提供的注解,目的是将一个继承了HttpServlet类的普通java类标注为一个Servlet
 * UserServlet使用了@WebServlet标注之后,就不需要在web.xml中配置了
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    //处理业务逻辑的userService
    private UserServiceI userService;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取所有的用户信息
        List<User> lstUsers = userService.getAllUser();
        request.setAttribute("lstUsers", lstUsers);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

    public void init() throws ServletException {
        //在Servlet初始化时获取Spring上下文对象(ApplicationContext)
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //从ApplicationContext中获取userService
        userService = (UserServiceI) ac.getBean("userService");
    }
}

 七,编辑index.jsp页面,用于突显查询到的用户音讯,内容如下:

<%@ page language="java" pageEncoding="UTF-8"%>
<%--引入JSTL核心标签库 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
    <head>
        <title>显示用户信息</title>
        <style type="text/css">
            table,td{
                border: 1px solid;
                border-collapse: collapse;
            }
        </style>
    </head>
    <body>
        <table>
            <tr>
                <td>用户ID</td>
                <td>用户名</td>
                <td>用户生日</td>
                <td>工资</td>
            </tr>
            <%--遍历lstUsers集合中的User对象 --%>
            <c:forEach var="user" items="${lstUsers}">
                <tr>
                    <td>${user.userId}</td>
                    <td>${user.userName}</td>
                    <td>${user.userBirthday}</td>
                    <td>${user.userSalary}</td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>

 8、执行maven
install命令编译项目,然后将品种布局到tomcat服务器中运转,注意,由于要动用Servlet3.0,所以必须将品种安插到tomcat7.x以上的服务器中去运营,如下所示:

  图片 28

  输入地方:http://localhost:8080/spring4-mybatis3/UserServlet 访问UserServlet,访问结果如下:

  图片 29

  可以看出,t_user表中的用户音信全体询问出来体现到页面上了。那样在web服务器中的测试也不荒谬通过了。

  以上就是Spring4.x与MyBatis3.x整合的全体内容了。编写那些组成例子花了不少日子,使用Maven编译时总是出现岂有此理的标题,有时候成功,有时候战败,反正很莫名其妙。若是遇到执行Maven
install操作不可以符合规律编译通过的事态:可以尝尝使用:Maven
clean→Clean项目→Maven install那多少个步骤去消除难题

 

网站地图xml地图