博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring框架 - 数据访问 单元作业
阅读量:6313 次
发布时间:2019-06-22

本文共 8286 字,大约阅读时间需要 27 分钟。

  hot3.png

#题目 1(12分) 根据本单介绍的Spring JDBC,事务管理,MyBatis等内容,分别使用Spring JDBC及MyBatis提供一个转帐服务(保证事务),提供一个transferMoney接口:

transferMoney(Long srcUserId, Long targetUserId, double count);// srcUserId及targetUserId为转帐用户标识

转帐涉及到的表(UserBalance)包含如下列:

userId:Long,代表用户标识;
balance:Doubcle,代表帐号余额。

#答案 ##初始化表结构 首先,根据表与表结构,创建表格与初始化数据内容

DROP TABLE IF EXISTS `UserBalance`;CREATE TABLE `UserBalance` (  `userId` int(11) NOT NULL AUTO_INCREMENT,  `balance` double DEFAULT NULL,  PRIMARY KEY (`userId`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;-- ------------------------------ Records of UserBalance-- ----------------------------INSERT INTO `UserBalance` VALUES ('1', '1000');INSERT INTO `UserBalance` VALUES ('2', '1000');

##定义Entity

package com.hava.homework.entity;/** * Created by yanfa on 2016/10/27. */public class UserBalance {    Long userId;    Double balance;    //Getter and Setter    public Long getUserId() {        return userId;    }    public void setUserId(Long userId) {        this.userId = userId;    }    public Double getBalance() {        return balance;    }    public void setBalance(Double balance) {        this.balance = balance;    }}

##定义UserBalanceDao接口

package com.hava.homework.repository;import com.hava.homework.entity.UserBalance;import java.util.List;/** * Created by yanfa on 2016/10/27. */public interface UserBalanceDaoInterface {    public List
findAll(); public void addMoney(Long userId,double count); public void subMoney(Long userId,double count);}

##分别实现 ###JdbcTemplate实现

package com.hava.homework.repository;import com.hava.homework.entity.UserBalance;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.BeanPropertyRowMapper;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Repository;import javax.sql.DataSource;import java.util.List;/** * Created by yanfa on 2016/10/27. */@Repositorypublic class UserBalanceJdbcTemplateDao implements UserBalanceDaoInterface {    private JdbcTemplate jdbcTemplate;    @Autowired    public void setDataSource(DataSource dataSource) {        this.jdbcTemplate = new JdbcTemplate(dataSource);    }    @Override    public List
findAll() { return this.jdbcTemplate.query("SELECT * FROM UserBalance",new BeanPropertyRowMapper(UserBalance.class)); } public void addMoney(Long userId, double count){ this.jdbcTemplate.update("UPDATE UserBalance SET balance=balance+? WHERE userId=?",count,userId); } public void subMoney(Long userId,double count){ this.jdbcTemplate.update("UPDATE UserBalance SET balance=balance-? WHERE userId=?",count,userId); } // srcUserId及targetUserId为转帐用户标识 public void transferMoney(Long srcUserId, Long targetUserId, double count){ System.out.println("transferMoney"); this.subMoney(srcUserId,count); throwException(); this.addMoney(targetUserId,count); } private void throwException() { throw new RuntimeException("Throw Exception"); }}

###MyBatis实现

package com.hava.homework.repository;import com.hava.homework.entity.UserBalance;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import java.util.List;/** * Created by yanfa on 2016/10/27. */public interface UserBalanceMyBatisDao extends UserBalanceDaoInterface{    @Update("UPDATE UserBalance SET balance=balance+#{param2} WHERE userId=#{param1} ")    public void addMoney(Long userId,double count);    @Update("UPDATE UserBalance SET balance=balance-#{param2} WHERE userId=#{param1} ")    public void subMoney(Long userId,double count);    @Select("SELECT * FROM UserBalance")    public List
findAll();}

##Service实现transferMoney 在TransferBalanceService实现transferMoney方法,并添加transaction

package com.hava.homework.service;import com.hava.homework.entity.UserBalance;import com.hava.homework.repository.UserBalanceDaoInterface;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.List;/** * Created by yanfa on 2016/10/27. */@Servicepublic class TransferBalanceService {    UserBalanceDaoInterface userBalanceDao;    public void setUserBalanceDao(UserBalanceDaoInterface userBalanceDao) {        this.userBalanceDao = userBalanceDao;    }    public List
findAll(){ return this.userBalanceDao.findAll(); } // srcUserId及targetUserId为转帐用户标识 @Transactional public void transferMoney(Long srcUserId, Long targetUserId, double count){ System.out.println("Class TransferBalanceService Method transferMoney"); this.userBalanceDao.subMoney(srcUserId,count); throwException(); this.userBalanceDao.addMoney(targetUserId,count); } private void throwException() { throw new RuntimeException("Throw Exception"); }}

##Spring配置文件

##运行主类

package com.hava.homework;import com.hava.homework.entity.UserBalance;import com.hava.homework.repository.UserBalanceJdbcTemplateDao;import com.hava.homework.repository.UserBalanceMyBatisDao;import com.hava.homework.service.TransferBalanceService;import org.springframework.context.ApplicationContext;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Created by yanfa on 2016/10/27. */public class UserBalanceMain {    public static void main(String [] args){        ApplicationContext context = new ClassPathXmlApplicationContext("homework-context.xml");        // get dao bean        UserBalanceJdbcTemplateDao userBalanceJdbcTemplateDao = context.getBean("userBalanceJdbcTemplateDao",UserBalanceJdbcTemplateDao.class);        UserBalanceMyBatisDao userBalanceMyBatisDao = context.getBean("userBalanceMyBatisDao",UserBalanceMyBatisDao.class);        // get service        TransferBalanceService transferBalanceService = context.getBean("transferBalanceService",TransferBalanceService.class);        System.out.println("transferBalanceService.setUserBalanceDao is userBalanceJdbcTemplateDao");        transferBalanceService.setUserBalanceDao(userBalanceJdbcTemplateDao);        for(UserBalance userBalance : transferBalanceService.findAll())            System.out.println("userBalance[id]:" +userBalance.getUserId() + " [balance]:" + userBalance.getBalance());        try {            transferBalanceService.transferMoney(1l, 2l, 100l);        }catch(Exception e)        {            System.out.println(e.toString());        }        for(UserBalance userBalance : transferBalanceService.findAll())            System.out.println("userBalance[id]:" +userBalance.getUserId() + " [balance]:" + userBalance.getBalance());        System.out.println("transferBalanceService.setUserBalanceDao is userBalanceMyBatisDao");        transferBalanceService.setUserBalanceDao(userBalanceMyBatisDao);        for(UserBalance userBalance : transferBalanceService.findAll())            System.out.println("userBalance[id]:" +userBalance.getUserId() + " [balance]:" + userBalance.getBalance());        try {            transferBalanceService.transferMoney(2l,1l,100l);        }catch(Exception e)        {            System.out.println(e.toString());        }        for(UserBalance userBalance : transferBalanceService.findAll())            System.out.println("userBalance[id]:" +userBalance.getUserId() + " [balance]:" + userBalance.getBalance());        ((ConfigurableApplicationContext) context).close();    }}

##运行结果

transferBalanceService.setUserBalanceDao is userBalanceJdbcTemplateDaouserBalance[id]:1 [balance]:900.0userBalance[id]:2 [balance]:900.0Class TransferBalanceService Method transferMoneyjava.lang.RuntimeException: Throw ExceptionuserBalance[id]:1 [balance]:900.0userBalance[id]:2 [balance]:900.0transferBalanceService.setUserBalanceDao is userBalanceMyBatisDaouserBalance[id]:1 [balance]:900.0userBalance[id]:2 [balance]:900.0Class TransferBalanceService Method transferMoney

##IDE中运行图片 输入图片说明

转载于:https://my.oschina.net/hava/blog/776252

你可能感兴趣的文章
Python-库安装
查看>>
Git笔记
查看>>
普通人如何从平庸到优秀,在到卓越
查看>>
SLAM数据集
查看>>
c#学习笔记05——数组&集合
查看>>
【图论算法】Dijstra&BFS
查看>>
注册和上传文件(头像)
查看>>
使用OVS
查看>>
键盘回收的几种方法
查看>>
Python(条件判断和循环)
查看>>
day4 linux安装python
查看>>
LeetCode Container With Most Water (Two Pointers)
查看>>
vue (v-if show 问题)
查看>>
https基础
查看>>
css3 canvas之刮刮卡效果
查看>>
并查集模板
查看>>
RESTful Mongodb
查看>>
BZOJ3237:[AHOI2013]连通图(线段树分治,并查集)
查看>>
如何提高Ajax性能
查看>>
Android--自定义加载框
查看>>