執行以下命令:css
mvn archetype:create -DgroupId=me.gacl -DartifactId=spring4-mybatis3 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
以下圖所示:
html
建立好的項目以下:java
編輯pom.xml文件mysql
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>me.gacl</groupId> 5 <artifactId>spring4-mybatis3</artifactId> 6 <packaging>war</packaging> 7 <version>1.0-SNAPSHOT</version> 8 <name>spring4-mybatis3 Maven Webapp</name> 9 <url>http://maven.apache.org</url>10 <dependencies>11 <dependency>12 <groupId>junit</groupId>13 <artifactId>junit</artifactId>14 <version>3.8.1</version>15 <scope>test</scope>16 </dependency>17 </dependencies>18 <build>19 <finalName>spring4-mybatis3</finalName>20 </build>21 </project>
修改 <name>spring4-mybatis3 Maven Webapp</name> 部分,把" Maven Webapp"這部分包含空格的內容去掉,不然Maven在編譯項目時會由於空格的緣由致使一些莫名其妙的錯誤出現,修改爲: <name>spring4-mybatis3</name> 。web
另外,把如下內容刪掉:spring
1 <dependency>2 <groupId>junit</groupId>3 <artifactId>junit</artifactId>4 <version>3.8.1</version>5 <scope>test</scope>6 </dependency>
這部分是junit的jar包依賴信息,這個版本過低了,咱們不使用這個Junit測試版本,修改事後的pom.xml內容以下:sql
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>me.gacl</groupId> 5 <artifactId>spring4-mybatis3</artifactId> 6 <packaging>war</packaging> 7 <version>1.0-SNAPSHOT</version> 8 <name>spring4-mybatis3</name> 9 <url>http://maven.apache.org</url>10 <dependencies>11 12 </dependencies>13 <build>14 <finalName>spring4-mybatis3</finalName>15 </build>16 </project>
具體操做步驟以下圖所示:數據庫
手動建立【src/main/java】、【src/test/resources】、【src/test/java】這三個source folder,以下圖所示:express
到此,項目搭建的工做就算是所有完成了。apache
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;
建立好的數據庫和表以下:
在網上找到了一個generator工具能夠根據建立好的數據庫表生成MyBatis的表對應的實體類,SQL映射文件和dao,找到generator工具根目錄下的generator.xml文件,這個文件是用來配置代碼生成規則的,以下圖所示:
編輯generator.xml文件,內容以下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 3 <generatorConfiguration> 4 <!-- 數據庫驅動包位置 --> 5 <classPathEntry location="E:\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar" /> 6 <!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />--> 7 <context id="DB2Tables" targetRuntime="MyBatis3"> 8 <commentGenerator> 9 <property name="suppressAllComments" value="true" />10 </commentGenerator>11 <!-- 數據庫連接URL、用戶名、密碼 -->12 <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/spring4_mybatis3" userId="root" password="XDP"> 13 <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">-->14 </jdbcConnection>15 <javaTypeResolver>16 <property name="forceBigDecimals" value="false" />17 </javaTypeResolver>18 <!-- 生成實體類的包名和位置,這裏配置將生成的實體類放在me.gacl.domain這個包下 -->19 <javaModelGenerator targetPackage="me.gacl.domain" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">20 <property name="enableSubPackages" value="true" />21 <property name="trimStrings" value="true" />22 </javaModelGenerator>23 <!-- 生成的SQL映射文件包名和位置,這裏配置將生成的SQL映射文件放在me.gacl.mapping這個包下 -->24 <sqlMapGenerator targetPackage="me.gacl.mapping" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">25 <property name="enableSubPackages" value="true" />26 </sqlMapGenerator>27 <!-- 生成DAO的包名和位置,這裏配置將生成的dao類放在me.gacl.dao這個包下 -->28 <javaClientGenerator type="XMLMAPPER" targetPackage="me.gacl.dao" targetProject="C:\Users\gacl\spring4-mybatis3\src\main\java">29 <property name="enableSubPackages" value="true" />30 </javaClientGenerator>31 <!-- 要生成那些表(更改tableName和domainObjectName就能夠) -->32 <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />33 </context>34 </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工具生成的代碼和映射文件:
一、生成的dao類
1 package me.gacl.dao; 2 3 import me.gacl.domain.User; 4 5 public interface UserMapper { 6 int deleteByPrimaryKey(String userId); 7 8 int insert(User record); 9 10 int insertSelective(User record);11 12 User selectByPrimaryKey(String userId);13 14 int updateByPrimaryKeySelective(User record);15 16 int updateByPrimaryKey(User record);17 }
生成的UserMapper是一個接口,裏面定義了一些操做t_user表的增刪改查方法。
二、生成的實體類
1 package me.gacl.domain; 2 3 import java.util.Date; 4 5 public class User { 6 private String userId; 7 8 private String userName; 9 10 private Date userBirthday;11 12 private Double userSalary;13 14 public String getUserId() {15 return userId;16 }17 18 public void setUserId(String userId) {19 this.userId = userId == null ? null : userId.trim();20 }21 22 public String getUserName() {23 return userName;24 }25 26 public void setUserName(String userName) {27 this.userName = userName == null ? null : userName.trim();28 }29 30 public Date getUserBirthday() {31 return userBirthday;32 }33 34 public void setUserBirthday(Date userBirthday) {35 this.userBirthday = userBirthday;36 }37 38 public Double getUserSalary() {39 return userSalary;40 }41 42 public void setUserSalary(Double userSalary) {43 this.userSalary = userSalary;44 }45 }
User類是t_user表的對應的實體類,User類中定義的屬性和t_user表中的字段一一對應。
三、生成的SQL映射文件
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="me.gacl.dao.UserMapper" > 4 <resultMap id="BaseResultMap" type="me.gacl.domain.User" > 5 <id column="user_id" property="userId" jdbcType="CHAR" /> 6 <result column="user_name" property="userName" jdbcType="VARCHAR" /> 7 <result column="user_birthday" property="userBirthday" jdbcType="DATE" /> 8 <result column="user_salary" property="userSalary" jdbcType="DOUBLE" /> 9 </resultMap>10 <sql id="Base_Column_List" >11 user_id, user_name, user_birthday, user_salary12 </sql>13 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >14 select 15 <include refid="Base_Column_List" />16 from t_user17 where user_id = #{userId,jdbcType=CHAR}18 </select>19 <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >20 delete from t_user21 where user_id = #{userId,jdbcType=CHAR}22 </delete>23 <insert id="insert" parameterType="me.gacl.domain.User" >24 insert into t_user (user_id, user_name, user_birthday, 25 user_salary)26 values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, 27 #{userSalary,jdbcType=DOUBLE})28 </insert>29 <insert id="insertSelective" parameterType="me.gacl.domain.User" >30 insert into t_user31 <trim prefix="(" suffix=")" suffixOverrides="," >32 <if test="userId != null" >33 user_id,34 </if>35 <if test="userName != null" >36 user_name,37 </if>38 <if test="userBirthday != null" >39 user_birthday,40 </if>41 <if test="userSalary != null" >42 user_salary,43 </if>44 </trim>45 <trim prefix="values (" suffix=")" suffixOverrides="," >46 <if test="userId != null" >47 #{userId,jdbcType=CHAR},48 </if>49 <if test="userName != null" >50 #{userName,jdbcType=VARCHAR},51 </if>52 <if test="userBirthday != null" >53 #{userBirthday,jdbcType=DATE},54 </if>55 <if test="userSalary != null" >56 #{userSalary,jdbcType=DOUBLE},57 </if>58 </trim>59 </insert>60 <update id="updateByPrimaryKeySelective" parameterType="me.gacl.domain.User" >61 update t_user62 <set >63 <if test="userName != null" >64 user_name = #{userName,jdbcType=VARCHAR},65 </if>66 <if test="userBirthday != null" >67 user_birthday = #{userBirthday,jdbcType=DATE},68 </if>69 <if test="userSalary != null" >70 user_salary = #{userSalary,jdbcType=DOUBLE},71 </if>72 </set>73 where user_id = #{userId,jdbcType=CHAR}74 </update>75 <update id="updateByPrimaryKey" parameterType="me.gacl.domain.User" >76 update t_user77 set user_name = #{userName,jdbcType=VARCHAR},78 user_birthday = #{userBirthday,jdbcType=DATE},79 user_salary = #{userSalary,jdbcType=DOUBLE}80 where user_id = #{userId,jdbcType=CHAR}81 </update>82 </mapper>
UserMapper.xml這個文件的內容是編寫操做t_user表的SQL語句,重點說一下UserMapper.xml配置中須要注意的幾個小細節問題:
一、UserMapper.xml的<mapper>標籤的namespace必須是UserMapper接口的全類名,既<mapper namespace="me.gacl.dao.UserMapper" >
二、UserMapper.xml的定義操做數據庫的<select><delete><update><insert>這些標籤的id屬性的值必須和UserMapper接口定義的方法名一致,以下圖所示:
之因此有上述說的這兩點要求,就是爲了可以讓MyBatis可以根據UserMapper接口和UserMapper.xml文件去自動實現UserMapper接口中定義的相關方法,這樣咱們就再也不須要針對UserMapper接口去編寫具體的實現代碼了。
首先咱們要在項目中加入咱們須要的相關jar包,咱們能夠到Maven的中央倉庫:http://search.maven.org/ 找到咱們要的相關jar包,以下圖所示:
咱們只須要在搜索框中輸入要找的jar包的名稱,點擊【SEARCH】按鈕,就能夠找到咱們要的jar包了。
一、添加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文件內容最終以下:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 <groupId>me.gacl</groupId> 5 <artifactId>spring4-mybatis3</artifactId> 6 <packaging>war</packaging> 7 <version>1.0-SNAPSHOT</version> 8 <name>spring4-mybatis3</name> 9 <url>http://maven.apache.org</url> 10 <dependencies> 11 <!-- 添加Spring-core包 --> 12 <dependency> 13 <groupId>org.springframework</groupId> 14 <artifactId>spring-core</artifactId> 15 <version>4.1.4.RELEASE</version> 16 </dependency> 17 <!-- 添加spring-context包 --> 18 <dependency> 19 <groupId>org.springframework</groupId> 20 <artifactId>spring-context</artifactId> 21 <version>4.1.4.RELEASE</version> 22 </dependency> 23 <!-- 添加spring-tx包 --> 24 <dependency> 25 <groupId>org.springframework</groupId> 26 <artifactId>spring-tx</artifactId> 27 <version>4.1.4.RELEASE</version> 28 </dependency> 29 <!-- 添加spring-jdbc包 --> 30 <dependency> 31 <groupId>org.springframework</groupId> 32 <artifactId>spring-jdbc</artifactId> 33 <version>4.1.4.RELEASE</version> 34 </dependency> 35 <!-- 爲了方便進行單元測試,添加spring-test包 --> 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-test</artifactId> 39 <version>4.1.4.RELEASE</version> 40 </dependency> 41 <!--添加spring-web包 --> 42 <dependency> 43 <groupId>org.springframework</groupId> 44 <artifactId>spring-web</artifactId> 45 <version>4.1.4.RELEASE</version> 46 </dependency> 47 <!--添加aspectjweaver包 --> 48 <dependency> 49 <groupId>org.aspectj</groupId> 50 <artifactId>aspectjweaver</artifactId> 51 <version>1.8.5</version> 52 </dependency> 53 <!-- 添加mybatis的核心包 --> 54 <dependency> 55 <groupId>org.mybatis</groupId> 56 <artifactId>mybatis</artifactId> 57 <version>3.2.8</version> 58 </dependency> 59 <!-- 添加mybatis與Spring整合的核心包 --> 60 <dependency> 61 <groupId>org.mybatis</groupId> 62 <artifactId>mybatis-spring</artifactId> 63 <version>1.2.2</version> 64 </dependency> 65 <!-- 添加servlet3.0核心包 --> 66 <dependency> 67 <groupId>javax.servlet</groupId> 68 <artifactId>javax.servlet-api</artifactId> 69 <version>3.0.1</version> 70 </dependency> 71 <dependency> 72 <groupId>javax.servlet.jsp</groupId> 73 <artifactId>javax.servlet.jsp-api</artifactId> 74 <version>2.3.2-b01</version> 75 </dependency> 76 <!-- jstl --> 77 <dependency> 78 <groupId>javax.servlet</groupId> 79 <artifactId>jstl</artifactId> 80 <version>1.2</version> 81 </dependency> 82 <!-- 添加mysql驅動包 --> 83 <dependency> 84 <groupId>mysql</groupId> 85 <artifactId>mysql-connector-java</artifactId> 86 <version>5.1.34</version> 87 </dependency> 88 <!-- 添加druid鏈接池包 --> 89 <dependency> 90 <groupId>com.alibaba</groupId> 91 <artifactId>druid</artifactId> 92 <version>1.0.12</version> 93 </dependency> 94 <!-- 添加junit單元測試包 --> 95 <dependency> 96 <groupId>junit</groupId> 97 <artifactId>junit</artifactId> 98 <version>4.12</version> 99 <scope>test</scope>100 </dependency>101 </dependencies>102 <build>103 <finalName>spring4-mybatis3</finalName>104 </build>105 </project>
一、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
二、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文件的配置很是簡單,就兩個配置。
三、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>
到此,相關的配置文件算是編寫完成了,以下圖所示:
通過以上兩個步驟,spring4與mybatis3的整合算是所有完成了。接下來咱們要作的工做就算進行單元測試,測試一下spring4與mybatis3的整合是否成功。
一、在src/main/java目錄下建立一個me.gacl.service包,而後在me.gacl.service包建立一個UserServiceI接口,以下所示:
1 package me.gacl.service; 2 3 import me.gacl.domain.User; 4 5 public interface UserServiceI { 6 7 /** 8 * 添加用戶 9 * @param user10 */11 void addUser(User user);12 13 /**14 * 根據用戶id獲取用戶15 * @param userId16 * @return17 */18 User getUserById(String userId);19 }
二、在src/main/java目錄下建立一個me.gacl.service.impl包,而後在me.gacl.service.impl包建立一個針對UserServiceI接口的實現類:UserServiceImpl,以下所示:
1 package me.gacl.service.impl; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Service; 5 import me.gacl.dao.UserMapper; 6 import me.gacl.domain.User; 7 import me.gacl.service.UserServiceI; 8 9 /**10 * @author gacl11 * 使用@Service註解將UserServiceImpl類標註爲一個service12 * service的id是userService13 */14 @Service("userService")15 public class UserServiceImpl implements UserServiceI {16 17 /**18 * 使用@Autowired註解標註userMapper變量,19 * 當須要使用UserMapper時,Spring就會自動注入UserMapper20 */21 @Autowired22 private UserMapper userMapper;//注入dao23 24 @Override25 public void addUser(User user) {26 userMapper.insert(user);27 }28 29 @Override30 public User getUserById(String userId) {31 return userMapper.selectByPrimaryKey(userId);32 }33 }
建立好的兩個類以下所示:
三、在src/test/java目錄下編寫單元測試類,新建一個me.gacl.test包,而後在這個包下建立一個MyBatisTest類,代碼以下:
1 package me.gacl.test; 2 3 import java.util.Date; 4 import java.util.UUID; 5 import me.gacl.domain.User; 6 import me.gacl.service.UserServiceI; 7 //import me.gacl.service.UserServiceI; 8 import org.junit.Before; 9 import org.junit.Test;10 import org.springframework.context.ApplicationContext;11 import org.springframework.context.support.ClassPathXmlApplicationContext;12 13 public class MyBatisTest {14 15 private UserServiceI userService;16 17 /**18 * 這個before方法在全部的測試方法以前執行,而且只執行一次19 * 全部作Junit單元測試時一些初始化工做能夠在這個方法裏面進行20 * 好比在before方法裏面初始化ApplicationContext和userService21 */22 @Before23 public void before(){24 //使用"spring.xml"和"spring-mybatis.xml"這兩個配置文件建立Spring上下文25 ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});26 //從Spring容器中根據bean的id取出咱們要使用的userService對象27 userService = (UserServiceI) ac.getBean("userService");28 }29 30 @Test31 public void testAddUser(){32 //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});33 //UserServiceI userService = (UserServiceI) ac.getBean("userService");34 User user = new User();35 user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));36 user.setUserName("白虎神皇xdp");37 user.setUserBirthday(new Date());38 user.setUserSalary(10000D);39 userService.addUser(user);40 }41 42 }
執行單元測試代碼,這時候會報以下錯誤:
錯誤提示是說沒有找到"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類,代碼以下:
1 package me.gacl.test; 2 3 import java.util.Date; 4 import java.util.UUID; 5 import me.gacl.domain.User; 6 import me.gacl.service.UserServiceI; 7 import org.junit.Test; 8 import org.junit.runner.RunWith; 9 import org.springframework.beans.factory.annotation.Autowired;10 import org.springframework.test.context.ContextConfiguration;11 import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;12 13 @RunWith(SpringJUnit4Cla***unner.class)14 //配置了@ContextConfiguration註解並使用該註解的locations屬性指明spring和配置文件以後,15 @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml" })16 public class MyBatisTestBySpringTestFramework {17 18 //注入userService19 @Autowired20 private UserServiceI userService;21 22 @Test23 public void testAddUser(){24 User user = new User();25 user.setUserId(UUID.randomUUID().toString().replaceAll("-", ""));26 user.setUserName("xdp_gacl_白虎神皇");27 user.setUserBirthday(new Date());28 user.setUserSalary(10000D);29 userService.addUser(user);30 }31 32 @Test33 public void testGetUserById(){34 String userId = "fb1c5941094e400b975f10d9a9d602a3";35 User user = userService.getUserById(userId);36 System.out.println(user.getUserName());37 }38 }
執行這兩個測試方法,是能夠正常測試經過的,以下所示:
到此,咱們框架的整合測試工做就算是所有經過了,整合成功。
一、編輯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()方法,以下所示:
1 package me.gacl.dao; 2 3 import java.util.List; 4 5 import me.gacl.domain.User; 6 7 public interface UserMapper { 8 int deleteByPrimaryKey(String userId); 9 10 int insert(User record);11 12 int insertSelective(User record);13 14 User selectByPrimaryKey(String userId);15 16 int updateByPrimaryKeySelective(User record);17 18 int updateByPrimaryKey(User record);19 20 /**獲取全部用戶信息21 * @return List<User>22 */23 List<User> getAllUser();24 }
三、在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()方法,以下:
1 package me.gacl.service; 2 3 import java.util.List; 4 5 import me.gacl.domain.User; 6 7 public interface UserServiceI { 8 9 /**10 * 添加用戶11 * @param user12 */13 void addUser(User user);14 15 /**16 * 根據用戶id獲取用戶17 * @param userId18 * @return19 */20 User getUserById(String userId);21 22 /**獲取全部用戶信息23 * @return List<User>24 */25 List<User> getAllUser();26 }
五、在UserServiceImpl類中實現getAllUser方法,以下:
1 package me.gacl.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 import me.gacl.dao.UserMapper; 8 import me.gacl.domain.User; 9 import me.gacl.service.UserServiceI;10 11 /**12 * @author gacl13 * 使用@Service註解將UserServiceImpl類標註爲一個service14 * service的id是userService15 */16 @Service("userService")17 public class UserServiceImpl implements UserServiceI {18 19 /**20 * 使用@Autowired註解標註userMapper變量,21 * 當須要使用UserMapper時,Spring就會自動注入UserMapper22 */23 @Autowired24 private UserMapper userMapper;//注入dao25 26 @Override27 public void addUser(User user) {28 userMapper.insert(user);29 }30 31 @Override32 public User getUserById(String userId) {33 return userMapper.selectByPrimaryKey(userId);34 }35 36 @Override37 public List<User> getAllUser() {38 return userMapper.getAllUser();39 }40 }
六、在src/main/java目錄下建立一個me.gacl.web.controller包,而後在me.gacl.web.controller下建立一個UserServlet,以下:
1 package me.gacl.web.controller; 2 3 import java.io.IOException; 4 import java.util.List; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.annotation.WebServlet; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 12 import org.springframework.context.ApplicationContext;13 import org.springframework.web.context.support.WebApplicationContextUtils;14 15 import me.gacl.domain.User;16 import me.gacl.service.UserServiceI;17 18 /**19 * @author gacl20 * @WebServlet是Servlet3.0提供的註解,目的是將一個繼承了HttpServlet類的普通java類標註爲一個Servlet21 * UserServlet使用了@WebServlet標註以後,就不須要在web.xml中配置了22 */23 @WebServlet("/UserServlet")24 public class UserServlet extends HttpServlet {25 26 //處理業務邏輯的userService27 private UserServiceI userService;28 29 public void doGet(HttpServletRequest request, HttpServletResponse response)30 throws ServletException, IOException {31 //獲取全部的用戶信息32 List<User> lstUsers = userService.getAllUser();33 request.setAttribute("lstUsers", lstUsers);34 request.getRequestDispatcher("/index.jsp").forward(request, response);35 }36 37 public void doPost(HttpServletRequest request, HttpServletResponse response)38 throws ServletException, IOException {39 this.doGet(request, response);40 }41 42 public void init() throws ServletException {43 //在Servlet初始化時獲取Spring上下文對象(ApplicationContext)44 ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());45 //從ApplicationContext中獲取userService46 userService = (UserServiceI) ac.getBean("userService");47 }48 }
七、編輯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>
八、執行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這三個步驟去解決問題