1. 程式人生 > >SpringMVC學習(四)——Spring、MyBatis和SpringMVC的整合

SpringMVC學習(四)——Spring、MyBatis和SpringMVC的整合

creat .com www. dispatch cte scanner scan fault framework

本文我再來講SpringMVC和MyBatis整合開發的方法,這樣的話,Spring、MyBatis和SpringMVC三大框架的整合開發我們就學會了。這裏我使用的Spring是Spring4.1.3這個版本(SpringMVC自然也是這個版本),MyBatis是MyBatis3.2.7這個版本。
為了更好的學習SpringMVC和MyBatis整合開發的方法,需要將SpringMVC和MyBatis進行整合。整合目標:控制層采用SpringMVC、持久層使用MyBatis實現。

需求

實現商品查詢列表,從mysql數據庫表中查詢商品信息。
為了實現這個需求,我們需要新建一個數據庫,例如springmvc,然後將以下sql腳本文件導入springmvc數據庫中:

  • springmvc.sql:

    /*
    Navicat MySQL Data Transfer
    
    Source Server         : localhost_3306
    Source Server Version : 50611
    Source Host           : localhost:3306
    Source Database       : springmvc
    
    Target Server Type    : MYSQL
    Target Server Version : 50611
    File Encoding         : 65001
    
    Date: 2016-05-09 19:45:13
    
    */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for items -- ---------------------------- DROP TABLE IF EXISTS `items`; CREATE TABLE `items` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL COMMENT ‘商品名稱‘, `price` float(10,1) NOT NULL COMMENT ‘商品定價‘, `detail` text COMMENT
    ‘商品描述‘, `pic` varchar(64) DEFAULT NULL COMMENT ‘商品圖片‘, `createtime` datetime NOT NULL COMMENT ‘生產日期‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of items -- ---------------------------- INSERT INTO `items` VALUES (‘1‘, ‘臺式機‘, ‘3000.0‘, ‘該電腦質量非常好!!!!‘, null, ‘2016-02-03 13:22:53‘); INSERT INTO `items` VALUES (‘2‘, ‘筆記本‘, ‘6000.0‘, ‘筆記本性能好,質量好!!!!!‘, null, ‘2015-02-09 13:22:57‘); INSERT INTO `items` VALUES (‘3‘, ‘背包‘, ‘200.0‘, ‘名牌背包,容量大質量好!!!!‘, null, ‘2015-02-06 13:23:02‘); -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) NOT NULL COMMENT ‘用戶名稱‘, `birthday` date DEFAULT NULL COMMENT ‘生日‘, `sex` char(1) DEFAULT NULL COMMENT ‘性別‘, `address` varchar(256) DEFAULT NULL COMMENT ‘地址‘, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (‘1‘, ‘王五‘, null, ‘2‘, null); INSERT INTO `user` VALUES (‘10‘, ‘張三‘, ‘2014-07-10‘, ‘1‘, ‘北京市‘); INSERT INTO `user` VALUES (‘16‘, ‘張小明‘, null, ‘1‘, ‘河南鄭州‘); INSERT INTO `user` VALUES (‘22‘, ‘陳小明‘, null, ‘1‘, ‘河南鄭州‘); INSERT INTO `user` VALUES (‘24‘, ‘張三豐‘, null, ‘1‘, ‘河南鄭州‘); INSERT INTO `user` VALUES (‘25‘, ‘陳小明‘, null, ‘1‘, ‘河南鄭州‘); INSERT INTO `user` VALUES (‘26‘, ‘王五‘, null, null, null);

如此一來items表就是這樣的:
技術分享圖片
由於需求決定,我們只對items表進行操作。

jar包管理

看一下SSM整合都用到了哪些jar包:

  1. Spring(包括SpringMVC)所需jar包
  2. MyBatis所需jar包
  3. mybatis-spring整合包
  4. 數據庫驅動包
  5. 第三方數據庫連接池

這樣一共需要31個jar包,我整理出來如下:
技術分享圖片
這裏我用的是dbcp數據庫連接池,當然也可以用c3p0等其他連接池,歸歸類後jar包就很有條理。

整合思路

關於SSM的架構可以簡單看一下下面的草圖:
技術分享圖片
可以看出,Spring在進行管理時,是很有條理的,每個層都由Spring管理,然後不同的層可以調用其它層,Handler調用service,service調用mapper等。根據這個架構,我們來總結一下整合的思路,根據這個調用關系,我們可以從下往上一步步整合。

  • Dao層
    1. SqlMapConfig.xml,空文件即可。
    2. applicationContext-dao.xml
      • a) 數據庫連接池
      • b) SqlSessionFactory對象,需要Spring和MyBatis的整合包。
      • c) 配置mapper文件掃描器。
  • Service層
    1. applicationContext-service.xml文件中配置包掃描器,掃描帶@service註解的類。
    2. applicationContext-trans.xml文件中配置事務。
  • 表現層
    1. 包掃描器,掃描帶@Controller註解的類。
    2. 配置註解驅動。
    3. 配置視圖解析器
  • web.xml
    在web.xml文件中配置前端控制器。

現在思路清晰了,接下來就開始整合了。在整合前先看一下我整合完的工程結構:
技術分享圖片

整合Dao層

整合Dao層也就是整合持久層,那麽需要Spring的核心包,持久層包,MyBatis包,數據庫以及連接池的包。

MyBatis全局配置文件

在classpath下創建mybatis/sqlMapConfig.xml這樣的MyBatis全局配置文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

可以看出,整合的時候,這個全局配置文件已經很清爽了,根本就沒啥東東了,因為數據源啊、mapper啊啥的都交給Spring去管理了。

配置Spring配置文件

配置完MyBatis的全局配置文件後,接下來就要配置Spring的配置文件了,Spring的配置文件我將分類寫在不同的文件中,都放在config/spring/目錄下了,這裏是對Dao的整合,所以起名applicationContext-dao.xml。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 數據庫連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    <!-- mapper配置 -->
    <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數據庫連接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加載mybatis的全局配置文件,雖然這個全局配置文件是空的,但是這個全局配置文件是必不可少的 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
    </bean>
    <!-- 配置Mapper掃描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.springmvc.mapper"/>
    </bean>

</beans>

註意:一定記得加載mybatis的全局配置文件,雖然這個全局配置文件是空的,但是這個全局配置文件是必不可少的。
可以看出,整合Dao層的時候主要配置了一下數據源、sqlSessionFactory和mapper掃描器, 這樣的話,數據源,sqlSessionFactory和mapper在tomcat啟動時就被Spring實例化到了容器中。
這兒db.properties該屬性配置文件的內容為:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

整合Service層

先把jar包導了再說,整合Service層需要配置事務了。

配置applicationContext-service.xml

這裏是第二個Spring的配置文件了,還是在config/spring文件夾下面,主要是用來配置所有的service的,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 配置包掃描器,掃描帶@Service註解的類 -->
    <context:component-scan base-package="com.itheima.springmvc.service"></context:component-scan>

</beans>

這兒只須配置包掃描器,專門掃描帶@Service註解的類。

配置applicationContext-trans.xml

這裏是第三個Spring的配置文件了,還是在config/spring文件夾下面,主要是用來配置Spring事務管理的,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 事務管理器,用的是Spring JDBC的事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數據源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行為 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.itheima.springmvc.service.*.*(..))" />
    </aop:config>

</beans>

有關Spring中事務的傳播行為,我也不是特別了解。也只是聽說過一嘴,先記錄如下:

  • propagation=”REQUIRED”:如果當前方法執行的時候,沒有事務要開啟事務,如果有事務,就在當前事務中執行。也可理解為當前方法被調用的時候沒有事務傳遞進來,就自己開啟事務
  • propagation=”SUPPORTS”:如果當前方法執行的時候,如果有事務,就在當前事務中執行,如果沒有事務就不開啟事務。也可理解為當前方法被調用的時候沒有事務傳遞進來,自己不開啟事務

整合表現層

上面提到過,SpringMVC是Spring的一個模塊,所以不需要整合,我們只需要加入SpringMVC所需的jar包即可。

配置處理器映射器、處理器適配器和視圖解析器

這裏使用註解的方式配置,因為註解的方式比較簡單。如此一來SpringMVC配置文件——springmvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.itheima.springmvc.controller"/>

    <!-- 配置一個註解驅動,如果配置此標簽,那麽就可以不用配置處理器映射器和處理器適配器 -->
    <mvc:annotation-driven />

    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

該配置文件依然在config/spring文件夾下面。

配置前端控制器

前端控制器要配置在WEB-INF/web.xml中,如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc-web</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 指定springmvc配置文件的路徑。如果不指定,默認為:/WEB-INF/${servlet-name}-servlet.xml -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

加載Spring容器

註意千萬不要忘記了在web.xml中添加Spring容器監聽器,加載Spring容器:

<!-- 初始化Spring容器 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

到此為止,Spring、MyBatis和SpringMVC三大框架就整合完了。整合完之後,接著就來實現我們的需求——商品列表的展示。

商品列表的展示

Dao層代碼的編寫,借助逆向工程生成po類及mapper

技術分享圖片

Service層代碼的編寫

之前提到過,service是用來調用mapper的,mapper是用來操作數據庫的,所以在Service層,我們首先要獲取mapper接口的代理對象,只不過在這裏我們通過Spring註入進來,然後通過這個代理對象去操作數據庫。
【第一步】,首先在com.itheima.springmvc.service包下編寫一個ItemService接口,如下:

public interface ItemService {
    List<Items> getItemList();
}

可以看出,這個接口和上面那個mapper接口其實是一樣的,當然並不是說一定一樣,只不過這裏要實現的邏輯都一樣而已。
【第二步】,在com.itheima.springmvc.service.impl包下編寫ItemService接口的實現類——ItemServiceImpl.java,如下:

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemsMapper itemsMapper;

    @Override
    public List<Items> getItemList() {
        ItemsExample example = new ItemsExample();
        List<Items> list = itemsMapper.selectByExampleWithBLOBs(example);
        return list;
    }

}

註意:selectByExampleWithBLOBs指代帶大文本那一列(即detail列)的方法。從items這個數據庫表的建表語句中可看出detail這列的數據類型是text,如下:
技術分享圖片

Web層代碼的編寫

在com.itheima.springmvc.controller包下編寫一個Controller類,如下:

@Controller
public class ItemController {

    @Autowired
    private ItemService itemService;

    @RequestMapping("/itemList")
    public ModelAndView getItemsList() {
        // 查詢商品列表
        List<Items> itemList = itemService.getItemList();
        // 把查詢結果傳遞給頁面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("itemList", itemList); // addObject方法相當於放到request域上
        // 設置邏輯視圖
        modelAndView.setViewName("itemList"); 
        // 返回結果
        return modelAndView;
    }
}

前臺itemList.jsp頁面還是第一篇博文中寫的那個,沒有變,就不寫了。

測試

最後在瀏覽器地址欄中輸入url地址——http://localhost:8080/springmvc-web/itemList.action,回車,即可看到如下效果:
技術分享圖片
這已然充分說明Spring、MyBatis和SpringMVC這三大框架就整合成功了.

SpringMVC學習(四)——Spring、MyBatis和SpringMVC的整合