1. 程式人生 > 其它 >springmvc和mybatis整合

springmvc和mybatis整合

spring將各層進行整合

1、spring管理持久層的mapper(相當於dao介面)

  mybatis和spring整合,通過spring管理mapper介面。

使用mapper的掃描器自動掃描mapper介面在spring中進行註冊。

2、spring管理業務層service,service中可以呼叫mapper介面。

spring進行事務控制。

3、spring管理表現層Handler,Handler中可以呼叫service介面。

mapper、service、Handler都是javabean。

一、mybatis和spring進行整合

  1、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>

  2、applicationContext-dao.xml:資料來源,SqlSessionFactory,mapper掃描

<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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
> <!-- 資料來源 SqlSessionFactory mapper掃描器 --> <!-- 1、引入資料庫連線屬性檔案 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2、配置C3P0連線池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 3、spring建立sqlSessionFactory物件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 載入mybatis的配置檔案 --> <property name="configLocation" value="mybatis/SqlMapConfig.xml" /> <!-- 資料來源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通過MapperScannerConfigurer進行mapper掃描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定掃描的包名 掃描多個包,使用半形逗號隔開 --> <property name="basePackage" value="com.xxx.springmvc.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
View Code

  3、mapper

    3.1、mapper.java

public interface ItemsMapperCustom {
    //商品查詢列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;

    3.2、mapper.xml

<!DOCTYPE mapper PUBLIC 
"-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.itcast.ssm.mapper.ItemsMapperCustom" >

   <!-- 定義商品查詢的sql片段,就是商品查詢條件 -->
   <sql id="query_items_where">
       <!-- 使用動態sql,通過if判斷,滿足條件進行sql拼接 -->
       <!-- 商品查詢條件通過ItemsQueryVo包裝物件 中itemsCustom屬性傳遞 -->
           <if test="itemsCustom!=null">
               <if test="itemsCustom.name!=null and itemsCustom.name!=''">
                   items.name LIKE '%${itemsCustom.name}%'
               </if>
           </if>
    
   </sql>
      
      <!-- 商品列表查詢 -->
      <!-- parameterType傳入包裝物件(包裝了查詢條件)
          resultType建議使用擴充套件物件
       -->
      <select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo"
           resultType="cn.itcast.ssm.po.ItemsCustom">
          SELECT items.* FROM items  
          <where>
              <include refid="query_items_where"></include>
          </where>
      </select>
      
</mapper>

二、spring管理service層

  1、定義service

public class ItemsServiceImpl implements ItemsService{
    
    @Autowired
    private ItemsMapperCustom itemsMapperCustom;

    @Override
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
            throws Exception {
        //通過ItemsMapperCustom查詢資料庫
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }

  2、spring配置(applicationContext-service.xml)

    2.1、spring中管理service

<bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl"/>

三、事務控制(applicationContext-transaction.xml)

<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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd 
        http://www.springframework.org/schema/context 
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop 
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    <!-- 事務管理器 
        對mybatis操作資料庫事務控制,spring使用jdbc的事務控制類
    -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 資料來源
        dataSource在applicationContext-dao.xml中配置了
         -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行為 
            REQUIRED:預設值,如果方法中有事務,使用方法中的事務,如果沒有事務,建立一個新事務。
            SUPPORTS:支援事務,如果方法中有事務,使用方法中的事務。如果沒有,不使用事務
            -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert*" 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:method name="select*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- aop -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.xxx.spring.service.impl.*.*(..))"/>
    </aop:config>
</beans>
View Code

四、整合springmvc

  1、springmvc.xml

<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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
      http://www.springframework.org/schema/context   
      http://www.springframework.org/schema/context/spring-context-3.2.xsd  
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
      
      
   <context:component-scan base-package="com.xxx.springmvc.controller"></context:component-scan>
    
    <mvc:annotation-driven></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>
View Code

  2、配置前端控制器(DispatcherServlet)web.xml

  <!-- springmvc前端控制器 -->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <!-- 
              contextConfigLocation:配置springmvc要載入的元件(處理器對映器、處理器介面卡、檢視解析器。。。) 
              contextConfigLocation:預設載入路徑:/WEB-INF/servlet-name-servlet.xml(springmvc-servlet.xml)
          -->
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <!-- 
      *.action:訪問以。action結尾的由DispatcherServlet解析
      /:所有訪問地址都由DispatcherServlet解析,對於靜態檔案的解析需要配置不讓DispatcherServlet解析,測試方式可以實現RESTful風格url
       -->
      <url-pattern>*.action</url-pattern>
  </servlet-mapping>

五、編寫Controller,編寫jsp(參照上一章)

@Controller
// 為了對url進行分類管理 ,可以在這裡定義根路徑,最終訪問url是根路徑+子路徑
// 比如:商品列表:/items/queryItems.action
@RequestMapping("/items")
public class ItemsController {

    @Autowired
    private ItemsService itemsService;

    // 商品查詢
    @RequestMapping("/queryItems")
    public ModelAndView queryItems(HttpServletRequest request,
            ItemsQueryVo itemsQueryVo) throws Exception {
        // 測試forward後request是否可以共享

        System.out.println(request.getParameter("id"));

        // 呼叫service查詢 資料庫,查詢商品列表
        List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);

        // 返回ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        // 相當 於request的setAttribut,在jsp頁面中通過itemsList取資料
        modelAndView.addObject("itemsList", itemsList);

        // 指定檢視
        // 下邊的路徑,如果在檢視解析器中配置jsp路徑的字首和jsp路徑的字尾,修改為
        // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
        // 上邊的路徑配置可以不在程式中指定jsp路徑的字首和jsp路徑的字尾
        modelAndView.setViewName("items/itemsList");

        return modelAndView;

    }
View Code

六、載入spring配置檔案(建議使用萬用字元載入上邊的配置檔案),web.xml

    <!-- 載入spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

最後將web.xml整體程式碼

<!-- 載入spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <!-- springmvc前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation配置springmvc載入的配置檔案(配置處理器對映器、介面卡等等) 如果不配置contextConfigLocation,預設載入的是/WEB-INF/servlet名稱-serlvet.xml(springmvc-servlet.xml) -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 第一種:*.action,訪問以.action結尾 由DispatcherServlet進行解析 
            第二種:/,所以訪問的地址都由DispatcherServlet進行解析,對於靜態檔案的解析需要配置不讓DispatcherServlet進行解析 
            使用此種方式可以實現 RESTful風格的url 
            第三種:/*,這樣配置不對,使用這種配置,最終要轉發到一個jsp頁面時, 仍然會由DispatcherServlet解析jsp地址,不能根據jsp頁面找到handler,會報錯。 -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    
    
    <!-- springmvc前端控制器,rest配置 -->
    <servlet>
        <servlet-name>springmvc_rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation配置springmvc載入的配置檔案(配置處理器對映器、介面卡等等) 
        如果不配置contextConfigLocation,預設載入的是/WEB-INF/servlet名稱-serlvet.xml(springmvc-servlet.xml) -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc_rest</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- post亂碼過慮器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
View Code