Transaction (Transaction) Brief Description

1. Definition

  • Transaction: a smallest unit of work that cannot be subdivided; usually a transaction corresponds to a complete business (for example, bank account transfer business, which is the smallest unit of work)
  • A complete business requires batch DML (insert, update, delete) statements to be jointly completed
  • Transactions are only related to DML statements, or DML statements have transactions. This is related to business logic, business logic is different, the number of DML statements is different

Two, application scenarios

Imagine an online shopping transaction, the payment process includes at least the following steps of database operations:

  • Update the inventory information of the products purchased by the customer
  • Save customer payment information-may include interaction with the banking system
  • Generate an order and save it in the database
  • Update user-related information, such as the number of purchases, etc.

Under normal circumstances, these operations will proceed smoothly, and eventually the transaction will be successful, and all database information related to the transaction will also be successfully updated. However, if an error occurs in any link in this series of processes, such as an abnormality in updating the product inventory information, or insufficient deposit in the customer's bank account, the transaction will fail. Once the transaction fails, all information in the database must remain unchanged before the transaction. For example, if the last step of updating user information fails and the transaction fails, then it must be ensured that the failed transaction does not affect the state of the database-inventory information has not been updated , The user has not paid, and the order has not been generated. Otherwise, the information in the database will be chaotic and unpredictable.
Database transactions are used to ensure the stability and predictability of transactions in this situation.

Three, code form representation

1. No affairs

Insert three data into the database, of which the second statement is wrong

/**
 * 没有事务
 * 
 * setAutoCommit(boolean b) : 
 * 			设置是否自动提交
 * 			参数为false则不提交,需要手动提交
 * 			参数为true则提交
 */
public class NoTransaction {
	public static void main(String[] args) {
		Connection connection = null;
		Statement statement = null;
		try {
			// 获取链接对象
			connection = DBUtil.getConnection();
			// 获取执行SQL语句的对象
			statement = connection.createStatement();

			/**
			 * 一次性添加三条记录
			 */
			statement.addBatch("insert into test(id,name) values(101,'无事务测试1')");
			// 故意写错字段,就是想让它出意外
			statement.addBatch("insert into test(id,nam) values(102,'无事务测试2')");
			statement.addBatch("insert into test(id,name) values(103,'无事务测试3')");
			/**
			 * 这种条件下,没有关闭自动提交,除了第二条错误的语句没有添加
			 * 另外两条成功添加
			 * 如果是转账业务的话,这种情况就会出错
			 */
			statement.executeBatch();
			System.out.println("执行成功");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(statement);
			DBUtil.close(connection);
		}
	}
}

2. There are affairs

/**
 * 关闭自动提交事务,手动提交,如果有错误,回滚。
 * 
 * setAutoCommit(boolean b) : 
 * 			设置是否自动提交
 * 			参数为false则不提交,需要手动提交
 * 			参数为true则提交
 */
public class Transaction {
	public static void main(String[] args) {
		Connection connection = null;
		Statement statement = null;
		try {
			// 链接对象
			connection = DBUtil.getConnection();
			/**
			 * 关闭自动提交,即使SQL语句正确,数据库表也不会发生变化
			 */
			connection.setAutoCommit(false);
			// 获取执行SQL语句的对象
			statement = connection.createStatement();
			/**
			 * 执行多条语句
			 */
			statement.addBatch("insert into test(id,name) values(201,'有事务测试1')");
			/**
			 * 错误语句,字段 nam 不正确
			 */
			statement.addBatch("insert into test(id,nam) values(202,'有事务测试2')");
			statement.addBatch("insert into test(id,name) values(203,'有事务测试3')");
			// 执行
			statement.executeBatch();
			System.out.println("执行成功");
			/**
			 * 手动提交事务
			 */
			connection.commit();
			// 打开自动提交
			connection.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				/**
				 	到这里说明有错误,需要回滚
					如果不回滚,直接打开自动提交的话,那么201和203还是会被添加进去
				 	因为没有提交之前的操作被保存到数据库缓存区,执行commit命令的时候,才会强制刷新到数据库中
					如果不回滚,等于没有使用事务一样,回滚就会跳转到执行操作之前
				 	所以 回滚之后会把对应的缓存区清空,然后再开启自动提交,就不会出现问题了
				 */
				connection.rollback();
				/**
				 * 再次把自动提交打开
				 */
				connection.setAutoCommit(true);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			DBUtil.close(statement);
			DBUtil.close(connection);
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/114001920