[JAVAEE]實驗06:基於XML和基於註解的聲明式事務管理方式模擬銀行轉賬程序 一、實驗目的: 二、實驗內容: 三、實驗要求: 四、設計 五、代碼 六、結果

一、實驗目的:

熟練掌握聲明式事務管理。

二、實驗內容:

編寫一個模擬銀行轉賬的程序,要求在轉賬時通過Spring對事務進行控制。

三、實驗要求:

分別使用基於XML和基於註解的聲明式事務管理方式來實現。

四、設計

1.數據表設計:id money name

2.Dao數據庫層:
根據用戶的id查詢用戶的餘額信息
根據用戶的id查詢的姓名
根據id存錢
根據id取錢

3.service層:
根據用戶的id查詢用戶的餘額信息
A給B轉賬(調用 根據id存錢、根據id取錢)
其內調用(根據用戶的id查詢的姓名)來展示用戶轉賬過程

4.controller層:
控制層(調用服務層方法,並在控制層完成事務操作的異常處理)

5.測試層:
XMLTest.java:
調用託管在Spring裏的控制層方法,獲取到控制層返回的結果信息
XML方式:在XML裏面利用AOP的操作,切點是Service,通知就是其事務的操作

AnnotationTest.java:
調用託管在Spring裏的控制層方法,獲取到控制層返回的結果信息
基於註釋:利用@Transactional在service方法處進行事務管理,在xml內掃描標籤

五、代碼

BankDao.java

package com.dao;
public interface BankDao {
    public double getMoneyById(String id);
    public String getNameById(String id);
    public void cashIn(String id, double money);
    public void cashOut(String id, double money);
}

BankDaoImpl.java

package com.dao;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.util.MyException;

//@Repository用於標註數據訪問組件,即DAO組件
@Repository("BankDao")

/*
 * 數據訪問層
 */
public class BankDaoImpl implements BankDao {
    
    
            
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    //根據用戶的id查詢用戶的餘額信息
    public double getMoneyById(String id) {
        String sql="select money from bank where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[] {id}, double.class);
    }
    
    @Override
    //根據用戶的id查詢的姓名
    public String getNameById(String id) {
        String sql="select name from bank where id=?";
        return jdbcTemplate.queryForObject(sql, new Object[] {id}, String.class);
    }
    
    @Override
    //根據id存錢
    public void cashIn(String id, double money) {
        String sql="update bank set money=money+? where id=?";
        jdbcTemplate.update(sql, money,id); 
    }
    
    
    @Override
    //根據id取錢
    public void cashOut(String id, double money) {

        double num=getMoneyById(id);//查詢餘額
        if(num>=money) {
            //餘額充足,可以取錢
            String sql="update bank set money=money-? where id=?";
            jdbcTemplate.update(sql, money,id);
        }else {
            //餘額不足,向外拋出異常
            System.out.println("餘額不足");
            throw new MyException("餘額不足");
    
        }
        

    }
    
        
    
}

BankService.java

package com.service;

public interface BankService {
    
    public void transferMoney(String inId,String outId, double money);

}

BankServiceImpl.java

package com.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dao.BankDao;
import com.util.MyException;
@Service("BankService")

/*
 * 服務層(對數據訪問層封裝,綁定事務操作)
 */

public class BankServiceImpl implements BankService{
    @Autowired
    private BankDao bankdao;
    
    //基於註釋的事務管理
    @Transactional(rollbackFor = (MyException.class))
//  這裏調用Dao層的save和delete方法,參數爲sql和param,等控制層在傳入sql語句
    public void transferMoney(String inId,String outId, double money) {
        
        String name1 = bankdao.getNameById(inId);
        String name2 = bankdao.getNameById(outId);
        
        double money1 = bankdao.getMoneyById(inId);
        double money2 = bankdao.getMoneyById(outId);
        
        
        
        System.out.println("轉賬前:"+name2+"的餘額:"+ money2 +"   "+ name1+"餘額:"+ money1);
        
        //轉賬的具體操作
        bankdao.cashIn(inId, money);
        bankdao.cashOut(outId, money);
        
        double money3 = bankdao.getMoneyById(inId);
        double money4 = bankdao.getMoneyById(outId);
        
        System.out.println("用戶1:"+name2+" >>>==轉賬==>>> "+ "用戶2:"+ name1);
        System.out.println("支付寶到賬:"+ money + "元");
        System.out.println("轉賬後:"+name2+"的餘額:"+ money4 +"   "+ name1+"餘額:"+ money3);
        
        
    }
    
}

BankController.java

package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.service.BankService;

@Controller("BankController")

/*
 * 控制層(調用服務層方法,並在控制層完成事務操作的異常處理)
 */
public class BankController {
    
    @Autowired
    private BankService bankService;
    public String test() {
        
        String message = "";
        
        try{
            bankService.transferMoney("002","001", 5);
            
            message = "事務正常";
            
            
        }catch(Exception e){
            
            message = "事務異常,回滾";
            e.printStackTrace();
            
        }
        return message;
    }
}

(一)基於XML的聲明式事務管理方式
XMLTest.java

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.controller.BankController;

/*
 * 測試類(調用託管在Spring裏的控制層方法,獲取到控制層返回的結果信息)
 * 
 * XML方式:在XML裏面利用AOP的操作,切點是Service,通知就是其事務的操作
 */

public class XMLTest {
    public static void main(String[] args) {
        
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("/com/xml/XMLstatementapplicationContext.xml");
        BankController ct = (BankController)appCon.getBean("BankController");
        
        String result = ct.test();
        System.out.println(result);
    }
}

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: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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 指定需要掃描的包(包括子包),使註解生效 -->
   <context:component-scan base-package="com"/>
   <!-- 配置數據源 -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- MySQL數據庫驅動 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!-- 連接數據庫的URL -->
        <property name="url" value="jdbc:mysql://localhost:3306/bank?characterEncoding=utf8"/>
        <!-- 連接數據庫的用戶名 -->
        <property name="username" value="root"/>
        <!-- 連接數據庫的密碼 -->
        <property name="password" value="363316495"/>
   </bean>
   <!-- 配置JDBC模板 -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
   </bean>
   <!-- 爲數據源添加事務管理器 -->
   <bean id="txManager"   
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
         <property name="dataSource" ref="dataSource" />   
   </bean> 
   
   <!-- 編寫通知:聲明事務 -->
   <tx:advice id="myAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!--事務的傳播行爲  -->
            <tx:method name="*" propagation="REQUIRED"/>

        </tx:attributes>
   </tx:advice>
   
   
   <!-- 編寫AOP,讓Spring自動對目標對象生成代理,需要使用AspectJ的表達式 -->
   <aop:config>
        <!-- 定義切入點,織入的對象是testService -->
        <aop:pointcut expression="execution(* com.service.*.*(..))" id="txPointCut"/>
        <!-- 切面:將切入點與通知關聯 -->
        <aop:advisor advice-ref="myAdvice" pointcut-ref="txPointCut"/>
   </aop:config>
</beans>

(二)基於註解的聲明式事務管理方式

AnnotationTest.java

package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

import com.controller.BankController;

/*
 * 測試類(調用託管在Spring裏的控制層方法,獲取到控制層返回的結果信息)
 * 
 * 基於註釋:利用@Transactional在service方法處進行事務管理,在xml內掃描標籤
 */

public class AnnotationTest {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("/com/xml/annotationstatementapplicationContext.xml");
        BankController ct = (BankController)appCon.getBean("BankController");
        String result = ct.test();
        System.out.println(result);
    }
}

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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 指定需要掃描的包(包括子包),使註解生效 -->
   <context:component-scan base-package="com"/>
   <!-- 配置數據源 -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- MySQL數據庫驅動 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!-- 連接數據庫的URL -->
        <property name="url" value="jdbc:mysql://localhost:3306/bank?characterEncoding=utf8"/>
        <!-- 連接數據庫的用戶名 -->
        <property name="username" value="root"/>
        <!-- 連接數據庫的密碼 -->
        <property name="password" value="363316495"/>
   </bean>
   <!-- 配置JDBC模板 -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
   </bean>
   <!-- 爲數據源添加事務管理器 -->
   <bean id="txManager"   
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
         <property name="dataSource" ref="dataSource" />   
   </bean> 
   <!-- 爲事務管理器註冊註解驅動 -->
   <tx:annotation-driven transaction-manager="txManager" />
</beans>

六、結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章