Spring的Jdbc事务-注解


一、拷贝必要的jar包到工程的lib目录

二、创建spring的配置文件并导入约束

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

三、准备数据库表和实体类

创建数据库:
create database spring;
use spring;
创建表:
create table account(
    id int primary key auto_increment,
    name varchar(40),
    money float
)character set utf8 collate utf8_general_ci;

package com.yiidian.domain;import java.io.Serializable;
/*** @author http://www.yiidian.com* */
public class Account implements Serializable{private Integer id;private String name;private Float money;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Float getMoney() {return money;}public void setMoney(Float money) {this.money = money;}@Overridepublic String toString() {return "Account [id=" + id + ", name=" + name + ", money=" + money+ "]";}}

四、编写业务层接口和实现类

AccountService:

package com.yiidian.service;import com.yiidian.domain.Account;
/*** @author http://www.yiidian.com* */
public interface AccountService {/*** 根据id查询账户信息* @param id* @return*/Account findAccountById(Integer id);//查/*** 转账* @param sourceName  转出账户名称* @param targeName       转入账户名称* @param money           转账金额*/void transfer(String sourceName,String targeName,Float money);//增删改
}

AccountServiceImpl:

package com.yiidian.service.impl;import org.springframework.transaction.annotation.Transactional;import com.yiidian.dao.AccountDao;
import com.yiidian.domain.Account;
import com.yiidian.service.AccountService;
/*** @author http://www.yiidian.com* */
@Transactional
public class AccountServiceImpl implements AccountService {private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}@Overridepublic Account findAccountById(Integer id) {return accountDao.findAccountById(id);}@Overridepublic void transfer(String sourceName, String targeName, Float money) {// 1.根据名称查询两个账户Account source = accountDao.findAccountByName(sourceName);Account target = accountDao.findAccountByName(targeName);// 2.修改两个账户的金额source.setMoney(source.getMoney() - money);// 转出账户减钱target.setMoney(target.getMoney() + money);// 转入账户加钱// 3.更新两个账户accountDao.updateAccount(source);//模拟异常//int i = 1 / 0;accountDao.updateAccount(target);}
}

注意:CustomerServiceImpl类上面有@Transactional注解,这就是注解事务的关键用法。

五、编写Dao接口和实现类

AccountDao:

package com.yiidian.dao;import com.yiidian.domain.Account;/*** * @author http://www.yiidian.com* */
public interface AccountDao {/*** 根据id查询账户信息* @param id* @return*/Account findAccountById(Integer id);/*** 根据名称查询账户信息* @return*/Account findAccountByName(String name);/*** 更新账户信息* @param account*/void updateAccount(Account account);
}

AccountDaoImpl:

package com.yiidian.dao.impl;import java.util.List;import org.springframework.jdbc.core.support.JdbcDaoSupport;import com.yiidian.dao.AccountDao;
import com.yiidian.domain.Account;
/*** * @author http://www.yiidian.com* */
public class AccountDaoImpl extends JdbcDaoSupport  implements AccountDao{@Overridepublic Account findAccountById(Integer id) {List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);return list.isEmpty()?null:list.get(0);}@Overridepublic Account findAccountByName(String name) {List<Account> list =  getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);if(list.isEmpty()){return null;}if(list.size()>1){throw new RuntimeException("结果集不唯一,不是只有一个账户对象");}return list.get(0);}@Overridepublic void updateAccount(Account account) {getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());}
}

AccountRowMapper:

package com.yiidian.dao.impl;import java.sql.ResultSet;
import java.sql.SQLException;import org.springframework.jdbc.core.RowMapper;import com.yiidian.domain.Account;
/*** 账户的封装类RowMapper的实现类* @author http://www.yiidian.com**/
public class AccountRowMapper implements RowMapper<Account>{@Overridepublic Account mapRow(ResultSet rs, int rowNum) throws SQLException {Account account = new Account();account.setId(rs.getInt("id"));account.setName(rs.getString("name"));account.setMoney(rs.getFloat("money"));return account;}
}

六、配置业务层和持久层,加上Spring事务管理

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="classpath:jdbc.properties" /></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource" /></bean><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClass}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><!-- 在AccountDaoImpl类直接注入dataSource即可 --><bean id="accountDao" class="com.yiidian.dao.impl.AccountDaoImpl"><property name="dataSource" ref="dataSource" /></bean><bean id="accountService" class="com.yiidian.service.impl.AccountServiceImpl"><property name="accountDao" ref="accountDao"></property></bean><!-- 配置一个事务管理器 --><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 注入DataSource --><property name="dataSource" ref="dataSource"></property></bean><!-- 开启spring对注解事务的支持 --><tx:annotation-driven transaction-manager="transactionManager"/></beans>

注意:必须使用这段xml来开启Spring注解事务才可以使用@Transactional注解。

 <!-- 开启spring对注解事务的支持 --><tx:annotation-driven transaction-manager="transactionManager"/>

七、编写测试类

package com.yiidian.test;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.yiidian.service.AccountService;/*** @author http://www.yiidian.com* */
public class JdbcTemplateDemo {/*** 添加操作*/@Testpublic void test1() {ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");AccountService accountService = (AccountService)ac.getBean("accountService");accountService.transfer("小苍", "小泽", 300f);}}

源码下载:http://pan.baidu.com/s/1eSOtYJC

Spring4.x()-Spring的Jdbc事务-注解相关推荐

  1. Spring4.x()--Spring的Jdbc事务-零配置

    Spring的Jdbc事务-零配置 一.拷贝必要的jar包到工程的lib目录 二.准备数据库表和实体类 创建数据库: create database spring; use spring; 创建表: ...

  2. Spring4 学习系列之——jdbc事务的基本实现和了解

    2019独角兽企业重金招聘Python工程师标准>>> Spring的事务管理   事务管理是企业级应用程序开发中必不可少的技术,用来确保数据的完整性和一致性,在开发中,我们是经常遇 ...

  3. Spring提取@Transactional事务注解的源码解析

    声明:本文是自己在学习spring注解事务处理源代码时所留下的笔记: 难免有错误,敬请读者谅解!!! 1.事务注解标签 <tx:annotation-driven /> 2.tx 命名空间 ...

  4. spring配置JDBC事务

    http://www.iteye.com/problems/2951 Spring+JDBC事务配置 悬赏:10 发布时间:2008-08-19 提问人:charity_lan (初级程序员) < ...

  5. Spring4.x()--Spring整合Jdbc的HelloWorld

    Spring整合Jdbc的HelloWorld 一.JdbcTemplate概述 它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装.spring框架为我们提供了很多的操作模 ...

  6. Spring的JDBC事务实现

    之前项目中有大量数据提交的需求,考虑了几个解决方案后还是觉得使用事务提交效率更高.数据插入也更方便. 一.首先,让我们来看看什么是事务 事务(Transaction)是并发控制的单元,是用户定义的一个 ...

  7. 【Spring】配置事务 注解方式与非注解方式

    Spring的事务配置非注解方式 <!--通知--><tx:advice id="txAdvice" transaction-manager="txTr ...

  8. Spring4.x()--Jdbc事务-XML

    Spring的Jdbc事务-XML 一.拷贝必要的jar包到工程的lib目录 二.创建spring的配置文件并导入约束 <?xml version="1.0" encodin ...

  9. 详解 Spring 声明式事务

    一.引言 Spring的事务机制包括声明式事务和编程式事务. 编程式事务管理:Spring推荐使用 TransactionTemplate,实际开发中使用声明式事务较多. 声明式事务管理:将我们从复杂 ...

最新文章

  1. Android采用Application总结一下
  2. 2021年春季学期-信号与系统-第六次作业参考答案-第七小题
  3. C++ string类型占几个字节
  4. 流媒体数据代理----Anychat
  5. 企业面试中关于MYSQL重点的28道面试题解答
  6. 每天进步一点点《SVD用于压缩》
  7. Progress Control控件的使用
  8. python安装第三方库时报错 SyntaxError: invalid syntax
  9. python-Python 3中字符串可以被改变吗?
  10. EVERTEC是如何利用大型机帮客户省钱?
  11. npoi 未将对象引用设置到对象的实例_new一个对象到底占了多少内存?
  12. java listview用法_Android ListView使用 | 学步园
  13. libusb-win32
  14. 迅捷pdf在线转换html,如何把PDF转换成HTML?迅捷PDF转换器
  15. 2022电工(初级)操作证考试题库及模拟考试
  16. 传奇泡点地图制作脚本
  17. 查看计算机.net环境版本,电脑怎么查看.NET Framework版本号?
  18. 英语日常短语积累(1)
  19. 深圳关内主要旅游景点地址和公交路线
  20. 基于词向量空间专业化的动词类跨语言归纳与迁移

热门文章

  1. STM32 影子寄存器
  2. c#读蓝牙数据_C#读取BWT901CL蓝牙传感器的数据
  3. DMA(direct memory access)控制方式
  4. 当集合a为空集时a的取值范围_1.2 集合间的基本关系20202021学年高一数学新教材配套学案(人教A版必修第一册)...
  5. 观察者模式与职责链模式的相同和不同_GOF设计模式(策略模式,职责链模式)...
  6. eclipse ssh mysql_Eclipse 配置SSH 详解
  7. 生成器函数,推导式,生成器表达式
  8. 第二阶段冲刺 每日站立会议 1/4
  9. linux 切换用户身份、su、sudo、/etc/sudoers
  10. 高效的JSON处理_ Jackson