JDBC事务还原点使用示例

/**
	 * JDBC事务还原点
	 * @param user
	 * @return
	 */
	private boolean jdbcSave(User user) {
		boolean success = false;
		System.out.printf("[Thread : %s] save user :%s\n", 
				Thread.currentThread().getName(), user);
		
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
			connection.setAutoCommit(false);
			//设置还原点
			Savepoint savepoint = connection.setSavepoint();
			PreparedStatement preparedStatement = connection.prepareStatement("insert into users(name) values(?);");
			preparedStatement.setString(1, user.getName());
			success = preparedStatement.executeUpdate() > 0;
			
			try {
				transactionalSave(user);
			} catch (Exception e) {
				connection.rollback(savepoint);
			}
			//提交事务
			connection.commit();
			//释放还原点
			connection.releaseSavepoint(savepoint);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(connection != null) {
				connection.close();
			}
		}
		return false;
	}

猜你喜欢

转载自blog.csdn.net/wangpf2011/article/details/83066146
今日推荐