mybatis、Spring整合(eclipse)以及事務管理

一、項目目錄

image

二、jar包

image

  • dbcp:鏈接池
  • pool:鏈接池
  • logging:日誌
  • log4j:日誌
  • mybatis-spring:用於SqlSession等相關操做
  • spring相關包
  • mybatis

三、web.xml配置

  • 能夠刪除本配置文件,本次測試用的是JUnit,不涉及網絡訪問,全部該配置文件並不須要
<?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>transactionDome</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>
 <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>

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

   <servlet>
       <servlet-name>springServlet</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value></param-value>
       </init-param>
       <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
       <servlet-name>springServlet</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

四、spring-mybatis.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-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-4.0.xsd">  
   <!-- 自動掃描 -->  
   <context:component-scan base-package="com.sysker.spring.dome" />  
   <!-- 引入配置文件 -->  
   <bean id="propertyConfigurer"  
       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
       <property name="location" value="classpath:jdbc.properties" />  
   </bean>  
  <!-- 鏈接池配置 -->  
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
       destroy-method="close">  
       <property name="driverClassName" value="${driver}" />  
       <property name="url" value="${url}" />  
       <property name="username" value="${username}" />  
       <property name="password" value="${password}" />  
       <!-- 初始化鏈接大小 -->  
       <property name="initialSize" value="${initialSize}"></property>  
       <!-- 鏈接池最大數量 -->  
       <property name="maxActive" value="${maxActive}"></property>  
       <!-- 鏈接池最大空閒 -->  
       <property name="maxIdle" value="${maxIdle}"></property>  
       <!-- 鏈接池最小空閒 -->  
       <property name="minIdle" value="${minIdle}"></property>  
       <!-- 獲取鏈接最大等待時間 -->  
       <property name="maxWait" value="${maxWait}"></property>  
   </bean>  
 
   <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->  
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
       <property name="dataSource" ref="dataSource" />  
       <!-- 自動掃描mapping.xml文件 -->  
       <property name="mapperLocations" value="classpath:com/sysker/spring/dome/mapping/*.xml"></property>  
   </bean>  
 
   <!-- DAO接口所在包名,Spring會自動查找其下的類 -->  
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
       <property name="basePackage" value="com.sysker.spring.dome.dao" />  
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
   </bean>  
 
   <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->  
   <bean id="transactionManager"  
       class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
       <property name="dataSource" ref="dataSource" />  
   </bean>  
   
   <!-- 配置事務管理模板:Spring爲了簡化事務管理的代碼而提供的類 -->
   <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
   	<property name="transactionManager" ref="transactionManager"></property>
   </bean>
 
</beans>

五、jdbc.properties配置

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8&amp;useSSL=false 

username=root

password=root


initialSize=0  

maxActive=20  

maxIdle=20  
 
minIdle=1  

maxWait=60000

六、log4j配置(日誌)

#定義LOG輸出級別  
log4j.rootLogger=INFO,Console,File  
#定義日誌輸出目的地爲控制檯  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
 
#文件大小到達指定尺寸的時候產生一個新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定輸出目錄  
log4j.appender.File.File = logs/ssm.log  
#定義文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

七、entity及mapping.xml

package com.sysker.spring.dome.entity;

public class Account {
    // 帳戶id
    private String id;
    // 帳號名
    private String name;
    // 餘額
    private String money;

    public Account() {
        super();
    }

    public Account(String id, String name, String money) {
        super();
        this.id = id;
        this.name = name;
        this.money = money;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMoney() {
        return money;
    }

    public void setMoney(String money) {
        this.money = money;
    }

}
  • 因爲直接mapping中直接用的是穿進來的參數,因此實體類也沒有用到
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.sysker.spring.dome.dao.AccountDao">
    <update id="inMoney">
    	update account set
    	money = money + #{arg1}
    	where name = #{arg0}
    </update>
    
    <update id="outMoney">
    	update account set
    	money = money - #{arg1}
    	where name = #{arg0}
    </update>
</mapper>

八、Dao

package com.sysker.spring.dome.dao;

public interface AccountDao {
    void outMoney(String out, String money);

    void inMoney(String in, String money);
}

九、service及serviceImpl

package com.sysker.spring.dome.service;

public interface AccountService {
    
    void transfer(String out, String in, String money);
}

service實現,包含了事務管理html

package com.sysker.spring.dome.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.sysker.spring.dome.dao.AccountDao;
import com.sysker.spring.dome.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService {
    
    @Autowired
    private AccountDao accountDao;
    
    @Autowired
    private TransactionTemplate transactionTemplate;
    
    @Override
    public void transfer(String out, String in, String money) {
        /**
         * 事務管理,execute()方法中建立了一個匿名內部類,在匿名內部類中操做業務,便可實現事務管理
         */
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountDao.outMoney(out, money);
                int i = 1/0;
                accountDao.inMoney(in, money);
                
            }
        });
        
        
    }

}

十、測試類

package com.sysker.spring.dome.test;


import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.sysker.spring.dome.service.AccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TestMybatis {
    private static Logger logger = Logger.getLogger(TestMybatis.class);
    @Resource
    private AccountService accountService = null;
    
    @Test
    public void test1() {
        accountService.transfer("aaa", "bbb", "200");
        logger.info("success");
        
    }
    
}

總結

  • 今天在慕課網學習,原本是打算實現事務管理的,但發現視頻中老師採用的是jdbc鏈接,因此就參考老師的思路,實現了mybatis-spring整合,過程雖然艱難,但確實收穫滿滿:
    • 一、對依賴注入有了更深的理解和認知,對spring有了更全面的認知,固然更多的仍是發現本身瞭解的太淺;
    • 二、多練習,多嘗試,多思考,多琢磨,多總結,當你踩完全部的坑,你就離成神之路不遠了
    • 三、我始終比較喜歡在bug中學習,每填掉一個坑都讓人感到興奮,同時也會收穫不少
相關文章
相關標籤/搜索