从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

时间:2020-11-29 17:53:33

技术发展日新月异,许多曾经拥有霸主地位的流行技术短短几年间已被新兴技术所取代。

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

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

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

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

接下来是选择Archetype。Maven提倡约定优于配置,对于源代码目录结构、配置文件位置、测试用户目录等内容都有既定的规则。遵循这些规则的好处就是不同开发者建立的项目结构是一致的,减少了在加入新项目时额外的熟悉和学习成本。

Maven内置的多种archetype可以针对不同类型的项目帮助开发者迅速勾勒出项目的骨架,例如Web项目可以选择maven-archetype-webapp,自动建立的目录中包括webapp等。这里从最基础的开始,选择maven-archetype-quickstart,其他选项保持不变,点击下一步。

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

这一步中填写项目的基本信息。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后点击完成。完成后生成的项目结构如下:

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

默认生成了src/main和src/test两个文件夹,根据约定,main放置项目源代码,test目录放置测试用例。默认还生成了两个演示文件(App.java和AppTest.java)可以直接删除。

本例中我们使用Mybatis操作MySQL数据库,并使用Spring集成,这些都需要添加依赖,即jar包。借助Maven,开发者不再需要去各个网站下载文件,而只需要配置pom.xml即可。打开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/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.example</groupId>
  5. <artifactId>petstore</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. <name>petstore</name>
  9. <url>http://maven.apache.org</url>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. </properties>
  13. <dependencies>
  14. <dependency>
  15. <groupId>junit</groupId>
  16. <artifactId>junit</artifactId>
  17. <version>3.8.1</version>
  18. <scope>test</scope>
  19. </dependency>
  20. </dependencies>
  21. </project>

其中,<dependencies>节点中的内容即依赖,Archetype默认添加了junit-3.8.1,我们按需要补充Spring、Mybatis、MySQL驱动等,完成后代码如下

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

注意这里使用了一个小技巧,spring有多个模块且使用相同的版本号,所以设置了一个<springframework.version>属性常量,如果需要修改版本只需要修改此处常量值即可。

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

本例中要实现的功能很简单,基于关系型数据库对某种商品做插入和查询的管理,商品仅有名称和价格两个属性。首先准备好数据库。

建库:

  1. CREATE SCHEMA `petstore` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ;

建表:

  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映射文件

添加代码文件后的目录结构如下:

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

三个文件的代码如下:

Product.java

  1. package com.example.petstore.model;
  2. public class Product {
  3. private int id;
  4. private String name;
  5. private float price;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public float getPrice() {
  19. return price;
  20. }
  21. public void setPrice(float price) {
  22. this.price = price;
  23. }
  24. }

ProductMapper.java

  1. package com.example.petstore.model;
  2. public interface ProductMapper {
  3. void addProduct(Product product);
  4. Product selectById(int id);
  5. }

Product.xml

  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. <resultMap type="com.example.petstore.model.Product" id="productMap">
  5. <id column="p_id" property="id" />
  6. <result column="p_name" property="name" />
  7. <result column="p_price" property="price" />
  8. </resultMap>
  9. <insert id="addProduct" parameterType="com.example.petstore.model.Product" useGeneratedKeys="true" keyProperty="id">
  10. insert into t_product(p_name,p_price) values(#{name},#{price})
  11. </insert>
  12. <select id="selectById" parameterType="int" resultType="com.example.petstore.model.Product" resultMap="productMap">
  13. select * from t_product where p_id=#{id}
  14. </select>
  15. </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

  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. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  13. destroy-method="close">
  14. <property name="driverClass" value="com.mysql.jdbc.Driver" />
  15. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/petstore?useUnicode=true&characterEncoding=UTF8" />
  16. <property name="user" value="root" />
  17. <property name="password" value="root123456" />
  18. <property name="minPoolSize" value="2" />
  19. <property name="maxPoolSize" value="10" />
  20. </bean>
  21. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  22. <property name="dataSource" ref="dataSource" />
  23. <property name="mapperLocations" value="classpath*:com/example/petstore/model/*.xml" />
  24. </bean>
  25. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  26. <property name="basePackage" value="com.example.petstore.model" />
  27. </bean>
  28. </beans>

其中,数据库的连接串及用户名、密码是我的测试机的设置,你需要按你的环境进行修改。

然后是测试用例,在src/test/java下添加类com.example.petstore.test.ProductTest.java

  1. package com.example.petstore.test;
  2. import static org.junit.Assert.*;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. import com.example.petstore.model.Product;
  9. import com.example.petstore.model.ProductMapper;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  12. public class ProductTest {
  13. @Autowired
  14. private ProductMapper productMapper;
  15. @Test
  16. public void insertAndSelect() {
  17. Product product1 = new Product();
  18. product1.setName("tom");
  19. product1.setPrice(99.9f);
  20. productMapper.addProduct(product1);
  21. assertTrue(product1.getId() > 0);
  22. Product product2 = productMapper.selectById(product1.getId());
  23. assertTrue(product2.getId() == product1.getId());
  24. assertTrue(product2.getName().equals(product1.getName()));
  25. }
  26. }

大功告成,本节中的所有代码都写完了,完成后的目录结构如下:

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

运行一下看看,在ProductTest.java上点右键 -> Run As -> Junit Test

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

测试通过,来看一下数据库里的内容:

从头开始基于Maven搭建SpringMVC+Mybatis项目(1)

总结

上述示例中完成了通过Maven创建简单项目、对数据库表的插入和读取操作,尽管没什么实用性,但也能够了解到了Mybatis的基本用法及与Spring的集成方式。

项目以jar包形式打包发布,这样做有利于代码复用,但是显然无法再增加Web部分的内容。传统的做法是另建一个Web项目并引用此项目,但我们接下来将使用Maven的聚合和继承功能构建包括一个数据库持久层模块和一个基于SpringMVC的Web模块的聚合项目,这些内容在下一节中介绍。

本文源码下载