程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> MyBatis進修教程(八)-Mybatis3.x與Spring4.x整合圖文詳解

MyBatis進修教程(八)-Mybatis3.x與Spring4.x整合圖文詳解

編輯:關於JAVA

MyBatis進修教程(八)-Mybatis3.x與Spring4.x整合圖文詳解。本站提示廣大學習愛好者:(MyBatis進修教程(八)-Mybatis3.x與Spring4.x整合圖文詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是MyBatis進修教程(八)-Mybatis3.x與Spring4.x整合圖文詳解正文


1、搭建開辟情況

1.1、應用Maven創立Web項目

  履行以下敕令:

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

  以下圖所示:

  

  創立好的項目以下:

  

  編纂pom.xml文件

 <project xmlns="http://maven.apache.org/POM/.." xmlns:xsi="http://www.w.org//XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">
 <modelVersion>..</modelVersion>
 <groupId>me.gacl</groupId>
 <artifactId>spring-mybatis</artifactId>
 <packaging>war</packaging>
 <version>.-SNAPSHOT</version>
 <name>spring-mybatis Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
 <dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>..</version>
 <scope>test</scope>
 </dependency>
 </dependencies>
 <build>
 <finalName>spring-mybatis</finalName>
 </build>
 </project>

  修正<name>spring4-mybatis3 Maven Webapp</name>部門,把"Maven Webapp"這部門包括空格的內容去失落,不然Maven在編譯項目時會由於空格的緣由招致一些莫明其妙的毛病湧現,修正成:<name>spring4-mybatis3</name>。

  別的,把以下內容刪失落:

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

  這部門是junit的jar包依附信息,這個版本太低了,我們不應用這個Junit測試版本,修正事後的pom.xml內容以下:

<project xmlns="http://maven.apache.org/POM/.." xmlns:xsi="http://www.w.org//XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">
 <modelVersion>..</modelVersion>
 <groupId>me.gacl</groupId>
 <artifactId>spring-mybatis</artifactId>
 <packaging>war</packaging>
 <version>.-SNAPSHOT</version>
 <name>spring-mybatis</name>
 <url>http://maven.apache.org</url>
 <dependencies>
 </dependencies>
 <build>
 <finalName>spring-mybatis</finalName>
 </build>
 </project>

1.2、將創立好的項目導入MyEclipse中

  詳細操作步調以下圖所示:

  

  

  

  

  

  手動創立【src/main/java】、【src/test/resources】、【src/test/java】這三個source folder,以下圖所示:

  

  到此,項目搭建的任務就算是全體完成了。

2、創立數據庫和表(針對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;

  創立好的數據庫和表以下:

  

3、應用generator對象生成代碼

  在網上找到了一個generator對象可以依據創立好的數據庫表生成MyBatis的表對應的實體類,SQL映照文件和dao,找到generator對象根目次下的generator.xml文件,這個文件是用來設置裝備擺設代碼生陳規則的,以下圖所示:

  

  編纂generator.xml文件,內容以下:

<?xml version="." encoding="UTF-"?>
 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration .//EN" "http://mybatis.org/dtd/mybatis-generator-config__.dtd">
 <generatorConfiguration>
 <!-- 數據庫驅動包地位 -->
 <classPathEntry location="E:\repository\mysql\mysql-connector-java\..\mysql-connector-java-...jar" /> 
 <!-- <classPathEntry location="C:\oracle\product\..\db_\jdbc\lib\ojdbc.jar" />-->
 <context id="DBTables" targetRuntime="MyBatis">
  <commentGenerator>
  <property name="suppressAllComments" value="true" />
  </commentGenerator>
  <!-- 數據庫鏈接URL、用戶名、暗碼 -->
  <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:/spring_mybatis" userId="root" password="XDP"> 
  <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost::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\spring-mybatis\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\spring-mybatis\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\spring-mybatis\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

  以下圖所示:


  

  適才我們在generator.xml文件中設置裝備擺設將生成的代碼和SQL映照文件放到"C:\Users\gacl\spring4-mybatis3\src\main\java"這個目次下,這個目次就是我們的spring4-mybatis3項目地點目次,我們刷新一下src/main/java目次,便可以看到生成的代碼和映照文件了,以下圖所示:

  

  生成的代碼和映照文件一行都不消改,可以直策應用到項目傍邊。上面我們看一眼由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表中的字段逐個對應。

  3、生成的SQL映照文件

<?xml version="." encoding="UTF-" ?>
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper .//EN" "http://mybatis.org/dtd/mybatis--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" >

  2、UserMapper.xml的界說操作數據庫的<select><delete><update><insert>這些標簽的id屬性的值必需和UserMapper接口界說的辦法名分歧,以下圖所示:

  

  之所以有上陳述的這兩點請求,就是為了可以或許讓MyBatis可以或許依據UserMapper接口和UserMapper.xml文件去主動完成UserMapper接口中界說的相干辦法,如許我們就不再須要針對UserMapper接口去編寫詳細的完成代碼了。

4、Spring與MyBatis整合

  起首我們要在項目中參加我們須要的相干jar包,我們可以到Maven的中心倉庫:http://search.maven.org/找到我們要的相干jar包,以下圖所示:

  

  我們只須要在搜刮框中輸出要找的jar包的稱號,點擊【SEARCH】按鈕,便可以找到我們要的jar包了。

4.1、添加Spring與Mybatis的相干jar包

  1、添加spring-core,輸出spring-core症結字停止查找,以下圖所示:

  

  找到關於spring-core的依附描寫信息,以下圖所示:

  

  將

<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包和它的相干依附包參加到我們的項目傍邊,以下所示:

  

  spring4.x與mybatis3.x所須要的相干jar包都可以采取上述所說的方法停止查找,然後添加到項目傍邊,添加完spring4.x與mybatis3.x相干jar包後,pom.xml文件內容終究以下:

<project xmlns="http://maven.apache.org/POM/.." xmlns:xsi="http://www.w.org//XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/.. http://maven.apache.org/maven-v__.xsd">
 <modelVersion>..</modelVersion>
 <groupId>me.gacl</groupId>
 <artifactId>spring-mybatis</artifactId>
 <packaging>war</packaging>
 <version>.-SNAPSHOT</version>
 <name>spring-mybatis</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <!-- 添加Spring-core包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!-- 添加spring-context包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!-- 添加spring-tx包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!-- 添加spring-jdbc包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!-- 為了便利停止單位測試,添加spring-test包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!--添加spring-web包 -->
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>...RELEASE</version>
  </dependency>
  <!--添加aspectjweaver包 -->
  <dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>..</version>
  </dependency>
  <!-- 添加mybatis的焦點包 -->
  <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>..</version>
  </dependency>
  <!-- 添加mybatis與Spring整合的焦點包 -->
  <dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>..</version>
  </dependency>
  <!-- 添加servlet.焦點包 -->
  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>..</version>
  </dependency>
  <dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>javax.servlet.jsp-api</artifactId>
  <version>..-b</version>
  </dependency>
  <!-- jstl -->
  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>.</version>
  </dependency>
  <!-- 添加mysql驅動包 -->
  <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>..</version>
  </dependency>
  <!-- 添加druid銜接池包 -->
  <dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>..</version>
  </dependency>
  <!-- 添加junit單位測試包 -->
  <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>.</version>
  <scope>test</scope>
  </dependency>
 </dependencies>
 <build>
  <finalName>spring-mybatis</finalName>
 </build>
 </project>

  

4.2、編寫相干設置裝備擺設文件

  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目次下創立一個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>

    到此,相干的設置裝備擺設文件算是編寫完成了,以下圖所示:

  

4.3、停止單位測試

  經由以上兩個步調,spring4與mybatis3的整合算是全體完成了。接上去我們要做的任務就算停止單位測試,測試一下spring4與mybatis3的整合能否勝利。

  1、在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目次下創立一個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);
 }
 }

    創立好的兩個類以下所示:

  

  3、在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(D);
  userService.addUser(user);
 }
 }

  履行單位測試代碼,這時候候會報以下毛病:

  

  毛病提醒是說沒有找到"me.gacl.test.MyBatisTest"這個類,這是由於我們沒有應用maven編譯項目中的類的原因。

  上面我們應用Maven編譯項目,選中項目標pom.xml文件→【Debug As】→【maven install】,以下所示:

  

編譯成果以下:

  

  在這裡說一下我履行Maven install以後碰到的成績,第一次履行Maven install敕令時,就湧現了以下一堆雜亂無章的毛病:

  

  後來我把項目刪失落,再從新導入項目,然後再履行Clean項目操作以後,以下圖所示:

  

  再履行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.junit.SpringJUnitClassRunner;
 @RunWith(SpringJUnitClassRunner.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(D);
  userService.addUser(user);
 }
 @Test
 public void testGetUserById(){
  String userId = "fbcebfdada";
  User user = userService.getUserById(userId);
  System.out.println(user.getUserName());
 }
 }

  履行這兩個測試辦法,是可以正常測試經由過程的,以下所示:

  
  

  到此,我們框架的整合測試任務就算是全體經由過程了,整分解功。

4.4、在web辦事器中停止測試

  1、編纂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>

  2、在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>

  4、在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、在UserServiceImpl類中完成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();
 }
 }

  6、在src/main/java目次下創立一個me.gacl.web.controller包,然後在me.gacl.web.controller下創立一個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是Servlet.供給的注解,目標是將一個繼續了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");
 }
 }

  7、編纂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以上的辦事器中去運轉,以下所示:

  

  輸出地址:http://localhost:8080/spring4-mybatis3/UserServlet拜訪UserServlet,拜訪成果以下:

  

  可以看到,t_user表中的用戶信息全體查詢出來顯示到頁面上了。如許在web辦事器中的測試也正常經由過程了。

  以上就是Spring4.x與MyBatis3.x整合的全體內容了。編寫這個整合例子花了很多時光,應用Maven編譯時老是湧現莫明其妙的成績,有時刻勝利,有時刻掉敗,橫豎很莫明其妙。假如碰到履行Maven install操作不克不及正常編譯經由過程的情形:可以測驗考試采取:Maven clean→Clean項目→Maven install這三個步調去處理成績

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved