Spring和MyBatis的整合詳解-配置文件&整合過程&代碼開發

配置文件

SSM整合參考文章(直接百度“SSM整合”)
http://my.oschina.net/sherwayne/blog/262616
1.需要哪些配置文件? (3個配置文件)

web.xml,springmvc的配置文件,spring和mybatis整合的配置文件
2.web.xml中的配置
(1)spring的配置(加載spring的相關配置),其實就是spring和mybatis整合的配置文件
第一步:加載listener

<!-- 配置 Spring -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 

第二步:指定spring配置文件的位置和名字(默認的方式和非默認的方式)。
contextConfigLocation
總結:可以默認將applicationContext.xml放在web-inf目錄下,也可以指定配置文件的名稱和位置。
從之前的項目中複製配置文件

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>

省略以後,相當於默認的方式

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> 

(2)spring mvc的配置
(a)默認的方式:在web.xml中配置springmvc的servlet的名字xxx,默認的springmvc配置文件名爲xx-servlet.xml
(b)非默認的方式:直接在web.xml中配置springmvc的servlet的時候,指定springmvc配置文件的位置和名字。

非默認的方式

<!-- Spring MVC servlet -->
  <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:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

(3)spring和mybatis整合的配置文件applicationContext.xml

spring 和 mybatis 的整合過程

在applicationContext.xml中進行整合
參考文章
http://my.oschina.net/sherwayne/blog/26261
1.這兩個配置項不再需要

(1)<aop:aspectj-autoproxy/>
(2)<context:annotation-config/>

參考文章:
http://chenjumin.iteye.com/blog/456351
參考文章:
http://blog.sina.com.cn/s/blog_872758480100wtfh.html
當使用 <context:component-scan/> 後,就可以將 <context:annotation-config/> 移除了
2.配置datasource

<!-- 配置數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!-- 初始化連接數量; -->
        <property name="initialSize" value="0" />
        <!-- 最大併發連接數 -->
        <property name="maxActive" value="20" />
        <!-- 最大空閒連接數 -->
        <property name="maxIdle" value="20" />
        <!-- 最小空閒連接數 -->
        <property name="minIdle" value="0" />
        <!-- 最大等待時長 -->
        <property name="maxWait" value="60000" />
        <!-- 超過時間限制是否回收 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超過時間限制多長; -->
        <property name="removeAbandonedTimeout" value="180"/>     
          
          
        <!-- 數據源連接參數配置; -->
        <property name="username" value="${db.username}"/>
        <property name="url" value="${db.url}"/>
        <property name="password" value="${db.password}"/>
        <property name="driverClassName" value="${db.driver}"/>
          
    </bean>

3.配置sessionfactory,並且指明mapper映射文件所在的包名。
id是固定的

    <!-- 配置SessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引入實體類  -->
        <property name="dataSource" ref="dataSource"/>    
   <!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
        <property name="mapperLocations">
        <list>        
            <!-- 映射文件位置  -->    
            <value>classpath:config/*.xml</value>
        </list>
        </property>
    </bean>

4.指明mapper接口所在的包名

<!-- 自動掃描mapper接口,注入sqlSessionFactory -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="mapper"/>
</bean>

5.配置事務管理器,注意:注入的是datasource屬性

<!-- 配置事務管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean> 

  <!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
  <!-- 定義切面 -->
<aop:config>
    <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

<!-- 聲明式事務 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">            
    <tx:attributes>
         <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
         <tx:method name="add" propagation="REQUIRED" read-only="true"/>
    </tx:attributes>        
</tx:advice>

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: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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
        <!-- 註解配置  -->
        <context:component-scan base-package="dao"></context:component-scan>
        <!-- 屬性佔位符  -->
        <context:property-placeholder location="classpath:db.properties"/>
        
        <!-- 配置數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!-- 初始化連接數量; -->
        <property name="initialSize" value="0" />
        <!-- 最大併發連接數 -->
        <property name="maxActive" value="20" />
        <!-- 最大空閒連接數 -->
        <property name="maxIdle" value="20" />
        <!-- 最小空閒連接數 -->
        <property name="minIdle" value="0" />
        <!-- 最大等待時長 -->
        <property name="maxWait" value="60000" />
        <!-- 超過時間限制是否回收 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超過時間限制多長; -->
        <property name="removeAbandonedTimeout" value="180"/>     
          
          
        <!-- 數據源連接參數配置; -->
        <property name="username" value="${db.username}"/>
        <property name="url" value="${db.url}"/>
        <property name="password" value="${db.password}"/>
        <property name="driverClassName" value="${db.driver}"/>
          
    </bean> 
    
    <!-- 配置SessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 引入實體類  -->
        <property name="dataSource" ref="dataSource"/>    
   <!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
        <property name="mapperLocations">
        <list>        
            <!-- 映射文件位置  -->    
            <value>classpath:config/*.xml</value>
        </list>
        </property>
    </bean>
    
    <!-- 自動掃描mapper接口,注入sqlSessionFactory -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="mapper"/>
    </bean>
    
    <!-- 配置事務管理器 -->
      <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean> 

<!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
      <!-- 定義切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
  
    <!-- 聲明式事務 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">            
        <tx:attributes>
             <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
             <tx:method name="add" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>        
    </tx:advice>
</beans>

代碼開發

1.由於已經整合了事務管理,獲取session的獲取和關閉的代碼不再需要。
將userMapper定義爲類的屬性,爲其設置setter,getter,通過@Resource注入即可。

2.將DAO註解爲一個@component

@Component
public class UserDAO {
    UserMapper userMapper;
    public UserMapper getUserMapper() {
        return userMapper;
    }
    @Resource
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public boolean isValid(User user) throws IOException {
        boolean flag = false;
        if (userMapper.isExists(user)==1) {
            flag = true;
        }
        return flag;
    }
}

3.在controller中,將userDAO定義爲累的屬性,爲其設置getter,setter,通過@Resource注入即可。

@Controller        
public class UserController {
    UserDAO userDAO;
    public UserDAO getUserDAO() {
        return userDAO;
    }
    @Resource
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @RequestMapping("/check.do")
    public String check(HttpSession session,User user) throws IOException {
        String path = "login";
        if (userDAO.isValid(user)) {
            session.setAttribute("name", user.getName());
            path = "welcome";
        }
        System.out.println("提交成功");
        return path;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章