交易所网站开发实战,wordpress 设置收费,wordpress 链接 排序,成都网站seo性价比高声明式事务 一、简介1、准备工作2、测试 二、声明式事务概念1、编程式事务2、声明式事务3、基于注解的声明式事务1.测试无事务情况2.加入事务①Transactional注解标识的位置②事务属性#xff1a;只读③事务属性#xff1a;超时④事务属性#xff1a;回滚策略⑤事务属性Transactional注解标识的位置②事务属性只读③事务属性超时④事务属性回滚策略⑤事务属性事务隔离级别⑥事务属性事务传播行为 一、简介
Spring 框架对 JDBC 进行封装使用 JdbcTemplate 方便实现对数据库操作
1、准备工作
①加入依赖 dependencies!-- 基于Maven依赖传递性导入spring-context依赖即可导入当前所需所有jar包 --dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion5.3.1/version/dependency!-- Spring 持久化层支持jar包 --!-- Spring 在执行持久化层操作、与持久化层技术进行整合过程中需要使用orm、jdbc、tx三个jar包 --!-- 导入 orm 包就可以通过 Maven 的依赖传递性把其他两个也导入 --dependencygroupIdorg.springframework/groupIdartifactIdspring-orm/artifactIdversion5.3.1/version/dependency!-- Spring 测试相关 --dependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion5.3.1/version/dependency!-- junit测试 --dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.12/versionscopetest/scope/dependency!-- MySQL驱动 --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.16/version/dependency!-- 数据源 --dependencygroupIdcom.alibaba/groupIdartifactIddruid/artifactIdversion1.0.31/version/dependency/dependencies②创建jdbc.properties
jdbc.drivercom.mysql.cj.jdbc.Driver
jdbc.urljdbc:mysql://localhost:3309/ssm?serverTimezoneUTC
jdbc.usernameroot
jdbc.password123456③配置Spring的配置文件
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd!-- 引入jdbc依赖--context:property-placeholder locationclasspath:jdbc.properties/context:property-placeholderbean iddataSource classcom.alibaba.druid.pool.DruidDataSourceproperty namedriverClassName value${jdbc.driver}/propertyproperty nameurl value${jdbc.url}/propertyproperty nameusername value${jdbc.username}/propertyproperty namepassword value${jdbc.password}/property/bean!-- 配置 JdbcTemplate用于test测试--bean classorg.springframework.jdbc.core.JdbcTemplateproperty namedataSource refdataSource/property/bean
/beans2、测试
①在测试类装配 JdbcTemplate
RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(classpath:spring-jdbc.xml)
public class JDBCTemplateTest {
Autowired
private JdbcTemplate jdbcTemplate;
}②测试增删改功能
Test
//测试增删改功能
public void testUpdate(){
String sql insert into t_emp values(null,?,?,?);
int result jdbcTemplate.update(sql, 张三, 23, 男);
System.out.println(result);
}③查询一条数据为实体类对象
Test
//查询一条数据为一个实体类对象
public void testSelectEmpById(){
String sql select * from t_emp where id ?;
Emp emp jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper
(Emp.class), 1);
System.out.println(emp);
}二、声明式事务概念
1、编程式事务
事务功能的相关操作全部通过自己编写代码来实现
Connection conn ...;try {
// 开启事务关闭事务的自动提交conn.setAutoCommit(false);
// 核心操作
// 提交事务conn.commit();}catch(Exception e){
// 回滚事务conn.rollBack();}finally{// 释放数据库连接conn.close();}编程式的实现方式存在缺陷 细节没有被屏蔽具体操作过程中所有细节都需要程序员自己来完成比较繁琐。 代码复用性不高如果没有有效抽取出来每次实现功能都需要自己编写代码代码就没有得到复 用。
2、声明式事务
既然事务控制的代码有规律可循代码的结构基本是确定的所以框架就可以将固定模式的代码抽取出来进行相关的封装。 封装起来后我们只需要在配置文件中进行简单的配置即可完成操作。
好处1提高开发效率好处2消除了冗余的代码好处3框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题进行了健壮性、性 能等各个方面的优化 所以我们可以总结下面两个概念编程式自己写代码实现功能声明式通过配置让框架实现功能
3、基于注解的声明式事务
①加入依赖 准备工作已加同简介中的准备工作 ②创建jdbc.properties 准备工作 已加同简介中的准备工作 ③配置Spring的配置文件 准备工作 已加同简介中的准备工作 ④创建表
CREATE TABLE t_book (
book_id int(11) NOT NULL AUTO_INCREMENT COMMENT 主键,
book_name varchar(20) DEFAULT NULL COMMENT 图书名称,
price int(11) DEFAULT NULL COMMENT 价格,
stock int(10) unsigned DEFAULT NULL COMMENT 库存无符号,
PRIMARY KEY (book_id)
) ENGINEInnoDB AUTO_INCREMENT3 DEFAULT CHARSETutf8;
insert into t_book(book_id,book_name,price,stock) values (1,斗破苍
穹,80,100),(2,斗罗大陆,50,100);
CREATE TABLE t_user (
user_id int(11) NOT NULL AUTO_INCREMENT COMMENT 主键,
username varchar(20) DEFAULT NULL COMMENT 用户名,
balance int(10) unsigned DEFAULT NULL COMMENT 余额无符号,
PRIMARY KEY (user_id)
) ENGINEInnoDB AUTO_INCREMENT2 DEFAULT CHARSETutf8;
insert into t_user(user_id,username,balance) values (1,admin,50);⑤创建组件 创建BookController
Controller
public class BookController {
Autowired
private BookService bookService;
public void buyBook(Integer bookId, Integer userId){
bookService.buyBook(bookId, userId);
}
}创建接口BookService
public interface BookService {/*** 买书* param userId* param bookId*/void buyBook(Integer userId, Integer bookId);
}创建实现类BookServiceImpl
Service
public class BookServiceImpl implements BookService {Autowiredprivate BookDao bookDao;Override/*** Transactional参数含义* readOnly只读* timeout超时时间超过设定的时间强制回滚*/Transactional(//readOnly true//timeout 3//noRollbackFor ArithmeticException.class//noRollbackForClassName java.lang.ArithmeticException//isolation Isolation.DEFAULTpropagation Propagation.REQUIRES_NEW)public void buyBook(Integer userId, Integer bookId) {//SECONDS:秒 MINUTES:分钟 DAYS:天 HOURS:小时try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}//查询图书的价格Integer price bookDao.getPriceByBookId(bookId);//更新图书的库存bookDao.updateStock(bookId);//更新用户的余额bookDao.updateBalance(userId, price);//System.out.println(1/0);}
}创建接口BookDao
public interface BookDao {/*** 根据图书的id查询图书的价格* param bookId* return*/Integer getPriceByBookId(Integer bookId);/*** 更新图书的库存* param bookId*/void updateStock(Integer bookId);/*** 更新用户的余额* param userId* param price*/void updateBalance(Integer userId, Integer price);
}创建实现类BookDaoImpl
Repository
public class BookDaoImpl implements BookDao {Autowiredprivate JdbcTemplate jdbcTemplate;Overridepublic Integer getPriceByBookId(Integer bookId) {String sql select price from t_book where book_id ?;return jdbcTemplate.queryForObject(sql, Integer.class, bookId);}Overridepublic void updateStock(Integer bookId) {String sql update t_book set stock stock - 1 where book_id ?;jdbcTemplate.update(sql, bookId);}Overridepublic void updateBalance(Integer userId, Integer price) {String sql update t_user set balance balance - ? where user_id ?;jdbcTemplate.update(sql, price, userId);}
}1.测试无事务情况
RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(classpath:tx-annotation.xml)
public class TxByAnnotationTest {Autowiredprivate BookController bookController;Testpublic void testBuyBook(){bookController.buyBook(1, 1);//bookController.checkout(1, new Integer[]{1,2});}}2.加入事务
在Spring的配置文件中添加配置
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/context xmlns:txhttp://www.springframework.org/schema/txxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://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-packageorg.example.spring/context:component-scan
!-- 导入外部组件--context:property-placeholder locationclasspath:jdbc.properties/context:property-placeholder
!-- 配置数据库--bean iddataSource classcom.alibaba.druid.pool.DruidDataSourceproperty namedriverClassName value${jdbc.driver}/propertyproperty nameurl value${jdbc.url}/propertyproperty nameusername value${jdbc.username}/propertyproperty namepassword value${jdbc.password}/property/bean
!-- 配置测试数据库的bean--bean classorg.springframework.jdbc.core.JdbcTemplateproperty namedataSource refdataSource/property/bean
!-- 配置事务管理器--bean idtransactionManagerclassorg.springframework.jdbc.datasource.DataSourceTransactionManagerproperty namedataSource refdataSource/property/bean
!-- 开启事务注解--tx:annotation-driven transaction-managertransactionManager/tx:annotation-driven
/beans
注意导入的名称空间需要 tx 结尾的那个。 ②添加事务注解 因为service层表示业务逻辑层一个方法表示一个完成的功能因此处理事务一般在service层处理 在BookServiceImpl的buybook()添加注解Transactional ③观察结果 由于使用了Spring的声明式事务更新库存和更新余额都没有执行
①Transactional注解标识的位置
Transactional标识在方法上只会影响该方法 Transactional标识的类上会影响类中所有的方法
②事务属性只读
①介绍 对一个查询操作来说如果我们把它设置成只读就能够明确告诉数据库这个操作不涉及写操作。这 样数据库就能够针对查询操作来进行优化。 ②使用方式
Transactional(readOnly true)
public void buyBook(Integer bookId, Integer userId) {
//查询图书的价格
Integer price bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId, price);
//System.out.println(1/0);
}③注意 对增删改操作设置只读会抛出下面异常 Caused by: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
③事务属性超时
①介绍 事务在执行过程中有可能因为遇到某些问题导致程序卡住从而长时间占用数据库资源。而长时间占用资源大概率是因为程序运行出现了问题可能是Java程序或MySQL数据库或网络连接等等。 此时这个很可能出问题的程序应该被回滚撤销它已做的操作事务结束把资源让出来让其他正常程序可以执行。 概括来说就是一句话超时回滚释放资源。 ②使用方式
Transactional(timeout 3)
public void buyBook(Integer bookId, Integer userId) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//查询图书的价格
Integer price bookDao.getPriceByBookId(bookId);
//更新图书的库存
bookDao.updateStock(bookId);
//更新用户的余额
bookDao.updateBalance(userId, price);
//System.out.println(1/0);
}③观察结果 执行过程中抛出异常 org.springframework.transaction.TransactionTimedOutException: Transaction timed out:
④事务属性回滚策略
①介绍 声明式事务默认只针对运行时异常回滚编译时异常不回滚。 可以通过Transactional中相关属性设置回滚策略
rollbackFor属性需要设置一个Class类型的对象回滚 举例 Transactional(rollbackFor CustomException.class) 通过将rollbackFor属性设置为CustomException.class告诉Spring只有当CustomException异常发生时才回滚事务。
rollbackForClassName属性需要设置一个字符串类型的全类名回滚 举例
Service
Transactional
public class UserService {Transactional(rollbackForClassName java.lang.RuntimeException)public void saveUser(User user) {// 保存用户信息的代码throw new RuntimeException(保存用户信息失败);}
}rollbackForClassName属性接受一个字符串类型的异常类名。当在事务执行期间抛出与指定异常类名匹配的异常时事务将会回滚。如果抛出的异常不匹配则事务不会回滚。 在上面的例子中如果saveUser()方法抛出RuntimeException异常事务将会回滚。 需要注意的是rollbackForClassName属性接受异常类名的字符串表示类名需要包含完整的包路径。另外也可以通过rollbackFor属性来指定异常类的Class对象实现相同的效果。
noRollbackFor属性需要设置一个Class类型的对象针对某个类不回滚noRollbackForClassName属性需要设置一个字符串类型的全类名
⑤事务属性事务隔离级别
①介绍 数据库系统必须具有隔离并发运行各个事务的能力使它们不会相互影响避免各种并发问题。一个事务与其他事务隔离的程度称为隔离级别。SQL标准中规定了多种事务隔离级别不同隔离级别对应不同的干扰程度隔离级别越高数据一致性就越好但并发性越弱。 隔离级别一共有四种
读未提交READ UNCOMMITTED 允许Transaction01读取Transaction02未提交的修改。读已提交READ COMMITTED、 要求Transaction01只能读取Transaction02已提交的修改。可重复读REPEATABLE READ 确保Transaction01可以多次从一个字段中读取到相同的值即Transaction01执行期间禁止其它事务对这个字段进行更新。串行化SERIALIZABLE 确保Transaction01可以多次从一个表中读取到相同的行在Transaction01执行期间禁止其它事务对这个表进行添加、更新、删除操作。可以避免任何并发问题但性能十分低下。 各个隔离级别解决并发问题的能力见下表
隔离级别脏读不可重复读幻读READ UNCOMMITTED有有有READ COMMITTED无有有REPEATABLE READ无无有SERIALIZABLE无无无②使用方式
Transactional(isolation Isolation.DEFAULT)//使用数据库默认的隔离级别
Transactional(isolation Isolation.READ_UNCOMMITTED)//读未提交
Transactional(isolation Isolation.READ_COMMITTED)//读已提交
Transactional(isolation Isolation.REPEATABLE_READ)//可重复读
Transactional(isolation Isolation.SERIALIZABLE)//串行化⑥事务属性事务传播行为
①介绍 当事务方法被另一个事务方法调用时必须指定事务应该如何传播。例如方法可能继续在现有事务中 运行也可能开启一个新事务并在自己的事务中运行。 ②测试 创建接口CheckoutService
public interface CheckoutService {
void checkout(Integer[] bookIds, Integer userId);
}创建实现类CheckoutServiceImpl
Service
public class CheckoutServiceImpl implements CheckoutService {Autowiredprivate BookService bookService;OverrideTransactional//一次购买多本图书public void checkout(Integer[] bookIds, Integer userId) {for (Integer bookId : bookIds) {bookService.buyBook(bookId, userId);}}
}在BookController中添加方法
Autowired
private CheckoutService checkoutService;
public void checkout(Integer[] bookIds, Integer userId){
checkoutService.checkout(bookIds, userId);
}在数据库中将用户的余额修改为100元 ③观察结果 可以通过Transactional中的propagation属性设置事务传播行为 修改BookServiceImpl中buyBook()上注解Transactional的propagation属性
Transactional(propagation Propagation.REQUIRED)默认情况表示如果当前线程上有已经开 启的事务可用那么就在这个事务中运行。经过观察购买图书的方法buyBook()在checkout()中被调 用checkout()上有事务注解因此在此事务中执行。所购买的两本图书的价格为80和50而用户的余额为100因此在购买第二本图书时余额不足失败导致整个checkout()回滚即只要有一本书买不 了就都买不了。
Transactional(propagation Propagation.REQUIRES_NEW)表示不管当前线程上是否有已经开启的事务都要开启新事务。同样的场景每次购买图书都是在buyBook()的事务中执行因此第一本图书购买成功事务结束第二本图书购买失败只在第二次的buyBook()中回滚购买第一本图书不受影响即能买几本就买几本。