mybatis、Spring整合(eclipse)以及交易管理

來源:互聯網
上載者:User

標籤:wired   layout   string   餘額   初始   映射   ips   init   匿名內部類   

1、項目目錄

2、jar包

  • dbcp:串連池
  • pool:串連池
  • logging:日誌
  • log4j:日誌
  • mybatis-spring:用於SqlSession等相關操作
  • spring相關包
  • mybatis
3、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>
4、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>  
5、jdbc.properties配置
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8&amp;useSSL=false username=rootpassword=rootinitialSize=0  maxActive=20  maxIdle=20   minIdle=1  maxWait=60000 
6、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
7、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>
8、Dao
package com.sysker.spring.dome.dao;public interface AccountDao {    void outMoney(String out, String money);    void inMoney(String in, String money);}
9、service及serviceImpl
package com.sysker.spring.dome.service;public interface AccountService {        void transfer(String out, String in, String money);}

service實現,包含了交易管理

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;@Servicepublic 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);                            }        });                    }}
10、測試類別
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整合,過程雖然艱難,但確實收穫滿滿:
    • 1、對依賴注入有了更深的理解和認知,對spring有了更全面的認知,當然更多的還是發現自己瞭解的太淺;
    • 2、多練習,多嘗試,多思考,多琢磨,多總結,當你踩完所有的坑,你就離成神之路不遠了
    • 3、我始終比較喜歡在bug中學習,每填掉一個坑都讓人感到興奮,同時也會收穫很多

mybatis、Spring整合(eclipse)以及交易管理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.