從頭開始基於Maven搭建SpringMVC+Mybatis項目(1)


技術發展日新月異,許多曾經擁有霸主地位的流行技術短短幾年間已被新興技術所取代。

Java的世界中,框架之爭可能比語言本身的改變更讓人關注。近幾年,SpringMVC憑借簡單輕便、開發效率高、與spring框架無縫整合等特點,逐漸擊敗前輩Struts/Struts2,成為最常用的Web框架。而Mybatis相對於hibernate,同樣具有開發簡單、效率高的優勢,而且對SQL的可控性更好,有利於性能調優,逐漸也積累了挑戰Hibernate的實力和人氣。

當前SpringMVC+Mybatis已經成為最流行的框架組合之一。

好的框架可以幫我們簡化開發,但實際的工作中還有大量的時間是花在編譯、測試、打包、部署等構建工作上,即使IDE變得越來越強大,但這些工作仍然需要我們一步一步去操作,而不能變成自動化的流水線作業。每天、每個項目重復這些步驟是毫無意義的,所以我們需要構建工具的幫助。構建工具的可選擇性並不是很多,Maven是目前是主流的選擇,它可以幫助開發者自動化構建、標准化結構、管理依賴等,極大的提高代碼以外的工作效率。

Maven、SpringMVC、Mybatis的組合優雅而強大,但對於初學者來說,把三者整合在一起並不是一件簡單的事。本文對這一復雜過程做拆解,從最基礎的步驟開始,一步步搭建起一個支持增、刪、改、分頁查詢的Web項目。

本文以Eclipse為開發工具,並需要安裝好Maven及Maven Integration for Eclipse插件,數據庫使用MySQL

如果沒有安裝過Maven可以參考:

http://blog.csdn.net/autfish/article/details/51008788

下面正式開始。

打開Eclipse,依次點擊 File -> New -> Maven Project

這一步不做任何修改,直接下一步

 

接下來是選擇Archetype。Maven提倡約定優於配置,對於源代碼目錄結構、配置文件位置、測試用戶目錄等內容都有既定的規則。遵循這些規則的好處就是不同開發者建立的項目結構是一致的,減少了在加入新項目時額外的熟悉和學習成本。

Maven內置的多種archetype可以針對不同類型的項目幫助開發者迅速勾勒出項目的骨架,例如Web項目可以選擇maven-archetype-webapp,自動建立的目錄中包括webapp等。這里從最基礎的開始,選擇maven-archetype-quickstart,其他選項保持不變,點擊下一步。

 

這一步中填寫項目的基本信息。Group Id和Artifact Id用於標注項目或模塊的坐標,Maven的一大功能是管理依賴(jar包),Maven的中央倉庫中有成千上萬的的開源項目,在倉庫中找到所需的項目文件就需要給每個項目分配一個唯一的標識。Group Id用於定義當前的項目,每個項目下按功能可能划分多個模塊,Artifact Id定義具體的模塊。例如Spring項目的Group Id是org.springframework,其下面划分了Artifact Id為spring-core、spring-context、spring-jdbc等多個模塊。

輸入Group Id和Artifact Id后點擊完成。完成后生成的項目結構如下:

默認生成了src/main和src/test兩個文件夾,根據約定,main放置項目源代碼,test目錄放置測試用例。默認還生成了兩個演示文件(App.java和AppTest.java)可以直接刪除。

本例中我們使用Mybatis操作MySQL數據庫,並使用Spring集成,這些都需要添加依賴,即jar包。借助Maven,開發者不再需要去各個網站下載文件,而只需要配置pom.xml即可。打開pom.xml,默認代碼如下:

 

[html]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  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/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.   
  5.     <groupId>com.example</groupId>  
  6.     <artifactId>petstore</artifactId>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <packaging>jar</packaging>  
  9.   
  10.     <name>petstore</name>  
  11.     <url>http://maven.apache.org</url>  
  12.   
  13.     <properties>  
  14.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  15.     </properties>  
  16.   
  17.     <dependencies>  
  18.         <dependency>  
  19.             <groupId>junit</groupId>  
  20.             <artifactId>junit</artifactId>  
  21.             <version>3.8.1</version>  
  22.             <scope>test</scope>  
  23.         </dependency>  
  24.     </dependencies>  
  25. </project>  

其中,<dependencies>節點中的內容即依賴,Archetype默認添加了junit-3.8.1,我們按需要補充Spring、Mybatis、MySQL驅動等,完成后代碼如下

 

 

[html]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. ...  
  2.       
  3.     <properties>  
  4.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  5.         <springframework.version>4.2.6.RELEASE</springframework.version>  
  6.     </properties>  
  7.   
  8.     <dependencies>  
  9.         <dependency>  
  10.             <groupId>junit</groupId>  
  11.             <artifactId>junit</artifactId>  
  12.             <version>4.12</version>  
  13.             <scope>test</scope>  
  14.         </dependency>  
  15.         <dependency>  
  16.             <groupId>org.springframework</groupId>  
  17.             <artifactId>spring-test</artifactId>  
  18.             <version>${springframework.version}</version>  
  19.             <scope>test</scope>  
  20.         </dependency>  
  21.         <dependency>  
  22.             <groupId>org.springframework</groupId>  
  23.             <artifactId>spring-core</artifactId>  
  24.             <version>${springframework.version}</version>  
  25.         </dependency>  
  26.         <dependency>  
  27.             <groupId>org.springframework</groupId>  
  28.             <artifactId>spring-context</artifactId>  
  29.             <version>${springframework.version}</version>  
  30.         </dependency>  
  31.         <dependency>  
  32.             <groupId>org.springframework</groupId>  
  33.             <artifactId>spring-beans</artifactId>  
  34.             <version>${springframework.version}</version>  
  35.         </dependency>  
  36.         <dependency>  
  37.             <groupId>org.springframework</groupId>  
  38.             <artifactId>spring-jdbc</artifactId>  
  39.             <version>${springframework.version}</version>  
  40.         </dependency>  
  41.         <dependency>  
  42.             <groupId>c3p0</groupId>  
  43.             <artifactId>c3p0</artifactId>  
  44.             <version>0.9.1.2</version>  
  45.         </dependency>  
  46.         <dependency>  
  47.             <groupId>org.mybatis</groupId>  
  48.             <artifactId>mybatis</artifactId>  
  49.             <version>3.4.1</version>  
  50.         </dependency>  
  51.         <dependency>  
  52.             <groupId>org.mybatis</groupId>  
  53.             <artifactId>mybatis-spring</artifactId>  
  54.             <version>1.3.0</version>  
  55.         </dependency>  
  56.         <dependency>  
  57.             <groupId>mysql</groupId>  
  58.             <artifactId>mysql-connector-java</artifactId>  
  59.             <version>5.1.18</version>  
  60.         </dependency>  
  61.     </dependencies>  
  62. </project>  

注意這里使用了一個小技巧,spring有多個模塊且使用相同的版本號,所以設置了一個<springframework.version>屬性常量,如果需要修改版本只需要修改此處常量值即可。

至此Maven配置完成,下面開始Mybatis部分。

本例中要實現的功能很簡單,基於關系型數據庫對某種商品做插入和查詢的管理,商品僅有名稱和價格兩個屬性。首先准備好數據庫。

建庫:

 

[sql]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. CREATE SCHEMA `petstore` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ;  

建表:

 

 

[sql]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. CREATE TABLE `petstore`.`t_product` (  
  2.   `p_id` INT NOT NULL AUTO_INCREMENT,  
  3.   `p_name` VARCHAR(45) NOT NULL,  
  4.   `p_price` FLOAT NOT NULL,  
  5.   PRIMARY KEY (`p_id`))  
  6. ENGINE = InnoDB  
  7. DEFAULT CHARACTER SET = utf8;  

Mybatis作為ORM框架,在這里的作用是把對t_product表的操作映射成對Java類的操作,依據約定,我們需要編碼三個文件:

 

Product.java - 映射實體類

ProductMapper.java - 接口,定義可調用的方法

Product.xml - 實際執行的SQL映射文件

添加代碼文件后的目錄結構如下:

三個文件的代碼如下:

Product.java

 

[java]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. package com.example.petstore.model;  
  2.   
  3. public class Product {  
  4.   
  5.     private int id;  
  6.     private String name;  
  7.     private float price;  
  8.   
  9.     public int getId() {  
  10.         return id;  
  11.     }  
  12.     public void setId(int id) {  
  13.         this.id = id;  
  14.     }  
  15.     public String getName() {  
  16.         return name;  
  17.     }  
  18.     public void setName(String name) {  
  19.         this.name = name;  
  20.     }  
  21.     public float getPrice() {  
  22.         return price;  
  23.     }  
  24.     public void setPrice(float price) {  
  25.         this.price = price;  
  26.     }  
  27. }  

ProductMapper.java

 

[java]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. package com.example.petstore.model;  
  2.   
  3. public interface ProductMapper {  
  4.   
  5.     void addProduct(Product product);  
  6.       
  7.     Product selectById(int id);  
  8. }  

Product.xml

 

 

[html]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  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="com.example.petstore.model.ProductMapper">  
  4.   
  5.     <resultMap type="com.example.petstore.model.Product" id="productMap">  
  6.         <id column="p_id" property="id" />  
  7.         <result column="p_name" property="name" />  
  8.         <result column="p_price" property="price" />  
  9.     </resultMap>  
  10.       
  11.     <insert id="addProduct" parameterType="com.example.petstore.model.Product" useGeneratedKeys="true" keyProperty="id">  
  12.         insert into t_product(p_name,p_price) values(#{name},#{price})  
  13.     </insert>  
  14.   
  15.     <select id="selectById" parameterType="int" resultType="com.example.petstore.model.Product" resultMap="productMap">  
  16.         select * from t_product where p_id=#{id}  
  17.     </select>  
  18. </mapper>  

可以看出,Product.java和ProductMapper.java非常普通,沒有任何與數據庫操作有關聯的內容。關鍵代碼在Product.xml中,其中,insert元素的id指明其匹配的方法是ProductMapper.java中的addProduct方法,參數類型是Product的實例,使用了數據庫自增字段,並且把自增的值綁定到id屬性上。select元素匹配的方法是selectById,resultMap元素定義了字段和Product類的屬性的對應關系。

 

代碼中並沒有生成ProductMapper的實現類,而是在運行期間動態創建代理類來完成實例化。

到這里Mybatis代碼就開發完成了,但是我們還想知道這些代碼是否可以正常工作,需要編寫一些測試用例。

如果僅使用Mybatis(而不使用Spring),那么還要添加Mybatis配置文件設置數據庫連接等,但這里不打算這么做,而是用Spring接管,所以接下來的代碼是Spring核心配置文件applicationContext.xml。注意這里是用於測試,所以文件將添加在src/test/java目錄。

applicationContext.xml

 

[html]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"    
  4.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"    
  5.     xmlns:context="http://www.springframework.org/schema/context"    
  6.     xsi:schemaLocation="    
  7.      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    
  8.      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  9.      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd    
  10.      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  11.      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
  12.   
  13.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  14.         destroy-method="close">  
  15.         <property name="driverClass" value="com.mysql.jdbc.Driver" />  
  16.         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/petstore?useUnicode=true&characterEncoding=UTF8" />  
  17.         <property name="user" value="root" />  
  18.         <property name="password" value="root123456" />  
  19.         <property name="minPoolSize" value="2" />  
  20.         <property name="maxPoolSize" value="10" />  
  21.     </bean>  
  22.   
  23.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  24.         <property name="dataSource" ref="dataSource" />  
  25.         <property name="mapperLocations" value="classpath*:com/example/petstore/model/*.xml" />  
  26.     </bean>  
  27.   
  28.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  29.         <property name="basePackage" value="com.example.petstore.model" />  
  30.     </bean>  
  31. </beans>  

 

其中,數據庫的連接串及用戶名、密碼是我的測試機的設置,你需要按你的環境進行修改。

然后是測試用例,在src/test/java下添加類com.example.petstore.test.ProductTest.java

 

[java]  view plain  copy
 
 print?在CODE上查看代碼片派生到我的代碼片
  1. package com.example.petstore.test;  
  2.   
  3. import static org.junit.Assert.*;  
  4.   
  5. import org.junit.Test;  
  6. import org.junit.runner.RunWith;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.test.context.ContextConfiguration;  
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  10.   
  11. import com.example.petstore.model.Product;  
  12. import com.example.petstore.model.ProductMapper;  
  13.   
  14. @RunWith(SpringJUnit4ClassRunner.class)  
  15. @ContextConfiguration(locations = "classpath:applicationContext.xml")  
  16. public class ProductTest {  
  17.   
  18.     @Autowired  
  19.     private ProductMapper productMapper;  
  20.       
  21.     @Test  
  22.     public void insertAndSelect() {  
  23.         Product product1 = new Product();  
  24.         product1.setName("tom");  
  25.         product1.setPrice(99.9f);  
  26.         productMapper.addProduct(product1);  
  27.         assertTrue(product1.getId() > 0);  
  28.           
  29.         Product product2 = productMapper.selectById(product1.getId());  
  30.         assertTrue(product2.getId() == product1.getId());  
  31.         assertTrue(product2.getName().equals(product1.getName()));  
  32.     }  
  33. }  

大功告成,本節中的所有代碼都寫完了,完成后的目錄結構如下:

 

運行一下看看,在ProductTest.java上點右鍵 -> Run As -> Junit Test

測試通過,來看一下數據庫里的內容:

總結

上述示例中完成了通過Maven創建簡單項目、對數據庫表的插入和讀取操作,盡管沒什么實用性,但也能夠了解到了Mybatis的基本用法及與Spring的集成方式。

項目以jar包形式打包發布,這樣做有利於代碼復用,但是顯然無法再增加Web部分的內容。傳統的做法是另建一個Web項目並引用此項目,但我們接下來將使用Maven的聚合和繼承功能構建包括一個數據庫持久層模塊和一個基於SpringMVC的Web模塊的聚合項目,這些內容在下一節中介紹。

 

本文源碼下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM