1. 程式人生 > >(四)Spring mvc 與Mybais整合

(四)Spring mvc 與Mybais整合

轉自:https://blog.csdn.net/yerenyuan_pku/article/details/72231763

為了更好的學習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包管理

我之前有寫過一篇Spring、Hibernate和Struts2整合的文章——hibernate-5.0.7+struts-2.3.24+spring-4.2.4三大框架整合,在整合的時候,我個人不喜歡亂,不喜歡啪嘰一下將所有jar包往lib中一扔,因為那樣沒有條理,所以在整合SSM的時候,我還是遵循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=yezi

整合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

關於如何使用MyBatis的逆向工程我就不再贅述了,如果不太清楚的童鞋請看一下我的這篇文章——!將生成的程式碼拷貝到我們自己的工程中即可,如下: 
這裡寫圖片描述

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,回車,即可看到如下效果: 
這裡寫圖片描述 為了更好的學習SpringMVC和MyBatis整合開發的方法,需要將SpringMVC和MyBatis進行整合。整合目標:控制層採用SpringMVC、持久層使用MyBatis實現。