1. 程式人生 > >Spring-mybatis整合配置常用的兩種方式

Spring-mybatis整合配置常用的兩種方式

1.使用mapper介面,定義了mapper介面,在mapper.xml中關聯mapper檔案的。

這裡寫圖片描述
其中mapper定義了介面,其類名與xml中的namespace一致,id與介面定義的方法名一直,這樣,把xml載入到spring中後,mybatis的初始化配置sqlsession時就會通過namespace+id的方式找到對應的sql進行執行,mybatis會自動匹配xml與mapper介面的對應關係,需要檔名稱一致。
這裡寫圖片描述

下面進行三個配置檔案的配置。

1.配置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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>website1</display-name>
<!-- 設定監聽,在web容器啟動時自動裝配ApplicationContext的配置資訊--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 設定Spring容器載入配置檔案路徑 --> <context-param
>
<param-name>contextConfigLocation</param-name> <param-value> classpath:config/springmvc-servlet.xml, classpath:config/ApplicationContext.xml </param-value> </context-param> <!-- 字元編碼過濾器 --> <filter> <filter-name>encodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <!-- 前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/springmvc-servlet.xml</param-value> </init-param> <!-- 這個配置檔案在容器啟動的時候 就載入 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 攔截請求 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <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> </web-app>

(2)、掃描控制層、自動注入以及檢視解析器的配置 springmvc-servlet.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"  
        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
        xmlns:cache="http://www.springframework.org/schema/cache"  
        xsi:schemaLocation="    
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd    
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd    
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd    
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd    
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd    
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    
        http://www.springframework.org/schema/cache  http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">  

        <!-- 註解驅動 -->  
        <mvc:annotation-driven />  
        <!-- <context:annotation-config /> -->  
        <!-- context:component-scan 具有annotation-config 的功能 -->  
        <!-- 掃描 控制層 -->  
        <context:component-scan base-package="com.website.controller"></context:component-scan>  
        <!-- 檢視解析器 -->  
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
                <property name="prefix" value="/WEB-INF/view/">  
                </property>  
                <property name="suffix" value=".jsp"></property>  
        </bean>  
</beans>

(3)spring代管sqlsessionFactory 、dao層介面動態代理以及事務的配置ApplicationContext.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
        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/tx     
                http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">  

        <!-- 載入配置JDBC檔案 -->  
        <context:property-placeholder location="classpath:db.properties" />  
        <!-- 資料來源 -->  
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
                <property name="driverClassName">  
                        <value>${jdbc.driverClassName}</value>  
                </property>  
                <property name="url">  
                        <value>${jdbc.url}</value>  
                </property>  
                <property name="username">  
                        <value>${jdbc.username}</value>  
                </property>  
                <property name="password">  
                        <value>${jdbc.password}</value>  
                </property>  
        </bean>  

        <!-- 開啟註解配置 即Autowried -->  
        <!-- <context:annotation-config/> -->  
        <!--其實component-scan 就有了annotation-config的功能即把需要的類註冊到了spring容器中 -->  
        <context:component-scan base-package="com.website.service" />  

        <!-- 在使用mybatis時 spring使用sqlsessionFactoryBean 來管理mybatis的sqlsessionFactory -->  
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
                <property name="dataSource" ref="dataSource" />  
                <!-- mybatis配置檔案路徑 -->  
                <property name="configLocation" value="" />  
                <!-- 實體類對映檔案路徑,這裡只有一個就寫死了,多個可以使用mybatis/*.xml來替代 -->  
                <property name="mapperLocations" value="classpath:mybatis/*.xml" />  
        </bean>  

        <!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0"> <ref bean="sqlSessionFactory"/>   
                </constructor-arg> </bean> -->  

        <!--動態代理實現 不用寫dao的實現 -->  
        <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
                <!-- 這裡的basePackage 指定了dao層介面路勁,這裡的dao介面不用自己實現 -->  
                <property name="basePackage" value="com.website.dao" />  
                <!-- 如果只有一個數據源的話可以不用指定,但是如果有多個數據源的話必須要指定 -->  
                <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->  
                <!--直接指定了sqlsessionTemplate名稱,這個和上面的其實是一樣的 -->  
                <!-- <property name="sqlSessionTemplateBeanName" value="sqlSession" /> -->  
        </bean>  

        <!--事務管理器 -->  
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
                <property name="dataSource" ref="dataSource" />  
        </bean>  
        <!-- 使用全註釋事務 -->  
        <tx:annotation-driven transaction-manager="transactionManager" />  
</beans>    

在MapperScannerConfigurer中,我們知道sqlSessionFactory的注入方式有四種,分別是sqlSessionFactory,sqlSessionFactoryBeanName,sqlSessionTemplate,sqlSessionTemplateBeanName,而sqlSessionFactory這種已經過時,所以我們用到的是sqlSessionFactoryBeanName,接下來說說這個的好處,為什麼要用到它!

原因1:

注入sqlSessionFactory,(可以不用配置)只有當配置多資料來源的時候,這時會有多個sqlSessionFactory,可以通過改屬性來指定哪一個sqlSessionFactory(綜合網上的總結)

原因2(重點):

注入sqlSessionFactory,後面的value是SqlSessionFactory的bean的名字,也就是sqlSessionFactory的id當我們的mapperscannerconfigurer啟動的時候,可能會出現我們的jdbc.properties檔案未被載入,這樣的話它拿到的DataSource就是錯誤的,因為像${jdbc.url}這類的屬性還沒有被替換掉,所以通過BeanName後處理的方式,當我們去用我們的Mybatis的時候,它才會去找我們對應的sqlSessionFactory,為了防止它提前初始化我們的sqlSessionFactory .

(4)如果使用單資料來源配置sqlSessionTemplateBeanName 這個屬性值需要額外加此段程式碼配置,(註釋的部分解開)

        <!-- 在使用mybatis時 spring使用sqlsessionFactoryBean 來管理mybatis的sqlsessionFactory -->  
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
                <property name="dataSource" ref="dataSource" />  
                <!-- mybatis配置檔案路徑 -->  
                <property name="configLocation" value="" />  
                <!-- 實體類對映檔案路徑,這裡只有一個就寫死了,多個可以使用mybatis/*.xml來替代 -->  
                <property name="mapperLocations" value="classpath:mybatis/userMapper.xml" />  
        </bean>  

        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
                <constructor-arg index="0">  
                        <ref bean="sqlSessionFactory" />  
                </constructor-arg>  
        </bean>  

        <!--動態代理實現 不用寫dao的實現 -->  
        <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
                <!-- 這裡的basePackage 指定了dao層介面路勁,這裡的dao介面不用自己實現 -->  
                <property name="basePackage" value="com.website.dao" />  
                <!-- 如果只有一個數據源的話可以不用指定,但是如果有多個數據源的話必須要指定 -->  
                <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->  
                <!--直接制定了sqlsessionTemplate名稱,這個和上面的其實是一樣的 -->  
                <property name="sqlSessionTemplateBeanName" value="sqlSession" />  
        </bean>  

注意如果是多資料來源則一定要使用sqlSessionFactoryBeanName 或sqlSessionTemplateBeanName 來指定具體的資料來源,不知道在上面的配置中有沒有注意到,如果使用sqlSessionTemplateBeanName 的話要來建立具體的例項並賦值給sqlSessionTemplateBeanName 這個屬性。

總結:

我們使用mapper介面的形式,在mapper介面名稱和xml的檔名稱對應且等於namespace一致,方法名和sql的id一致,這樣我們在配置掃描器

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
                <property name="dataSource" ref="dataSource" />  
                <!-- mybatis配置檔案路徑 -->  
                <property name="configLocation" value="" />  
                <!-- 實體類對映檔案路徑,這裡只有一個就寫死了,多個可以使用mybatis/*.xml來替代 -->  
                <property name="mapperLocations" value="classpath:mybatis/*.xml" />  
        </bean>  

就能掃描到我們的xml檔案,然後我們在配置

<bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
                <!-- 這裡的basePackage 指定了dao層介面路勁,這裡的dao介面不用自己實現 -->  
                <property name="basePackage" value="com.website.dao" />  
                <!-- 如果只有一個數據源的話可以不用指定,但是如果有多個數據源的話必須要指定 -->  
                <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->  
                <!--直接制定了sqlsessionTemplate名稱,這個和上面的其實是一樣的 -->  
                <property name="sqlSessionTemplateBeanName" value="sqlSession" />  
        </bean>  

就可以將我們的mapper介面檔案掃描到,mybatis將他們匹配生成對應關係,我們在呼叫的時候,通過namespace+id的方式進行呼叫sql語句。所以你的對映檔案的namespace 必須是介面的類全名稱而id 必須是介面中的方法名稱,這樣動態代理就能找到路勁了也有了引數了。

二、使用SqlSessionTemplate進行呼叫sql語句的配置。

1mybatis核心配置

<?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:tx="http://www.springframework.org/schema/tx"  
    xmlns:context="http://www.springframework.org/schema/context"  
    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/tx   
                http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">  

    <!-- 載入配置JDBC檔案 -->  
    <context:property-placeholder location="classpath:db.properties" />  
    <!-- 資料來源 -->  
    <bean id="dataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName">  
            <value>${jdbc.driverClassName}</value>  
        </property>  
        <property name="url">  
            <value>${jdbc.url}</value>  
        </property>  
        <property name="username">  
            <value>${jdbc.username}</value>  
        </property>  
        <property name="password">  
            <value>${jdbc.password}</value>  
        </property>  
    </bean>  

    <!-- 開啟註解配置 即Autowried -->  
    <!--component-scan擁有 annotation-config的功能即注入需要的類到spring容器中 -->  
    <!--<context:annotation-config/> -->  
    <!--使用自動注入的時候要 新增他來掃描bean之後才能在使用的時候 -->  
    <context:component-scan base-package="com.website.service ,com.website.dao" />  

    <!-- 在使用mybatis時 spring使用sqlsessionFactoryBean 來管理mybatis的sqlsessionFactory -->  
    <!-- 而像這種使用介面實現的方式 是使用sqlsessionTemplate來進行操作的,他提供了一些方法 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- mybatis配置檔案路徑 -->  
        <property name="configLocation" value="" />  
        <!-- 實體類對映檔案路徑,在開發中對映檔案肯定是多個所以使用mybatis/*.xml來替代 -->  
        <property name="mapperLocations" value="classpath:mybatis/UserMapping.xml" />  
    </bean>  

    <!--其實這裡類的例項就是mybatis中SQLSession -->  
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0">  
            <ref bean="sqlSessionFactory" />  
        </constructor-arg>  
    </bean>  

    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
    <!--使用全註釋事務 -->  
    <tx:annotation-driven transaction-manager="transactionManager" />  
</beans>  

其中少了這樣的配置,去掉了動態代理的實現,不採用介面的形式。

<!--動態代理實現 不用寫dao的實現 -->  
        <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
                <!-- 這裡的basePackage 指定了dao層介面路勁,這裡的dao介面不用自己實現 -->  
                <property name="basePackage" value="com.website.dao" />  
                <!-- 如果只有一個數據源的話可以不用指定,但是如果有多個數據源的話必須要指定 -->  
                <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> -->  
                <!--直接制定了sqlsessionTemplate名稱,這個和上面的其實是一樣的 -->  
                <property name="sqlSessionTemplateBeanName" value="sqlSession" />  
        </bean>  

這樣就必須我們自己實現mybatis的sql語句的呼叫,這樣我們需要在dao層注入在配置檔案中例項化的sqlSession這個bean,使用它進行selectOne,selectList()的呼叫,傳入namespace.id的引數,確定唯一的sql語句。

package com.website.dao;  

import java.util.Map;  

import org.mybatis.spring.SqlSessionTemplate;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Repository;  

/** 
 * @author WHD data 2016年6月5日 
 */  
@Repository("userDao")  
public class UserDao {  
    @Autowired  
    private SqlSessionTemplate sqlSession;  

    public void saveUser(Map<String, String> map) {  
        int end = sqlSession.insert("com.website.userMapper.insertUser", map);  
        System.out.println("end" + end);  
    }  
}  

這裡進行sqlSession.insert方法呼叫,第一個引數是string型,statement的id,第二個引數是param。