我正试图围绕Java Transactions API (JTA) 及其实现之一 Bitronix 下的价值。但是随着我对文档的深入挖掘,我不禁想到了以下简单的示例:
public interface Transactional {
public void commit(Object);
public void rollback();
}
public class TransactionalFileWriter extends FileWriter implements Transactional {
@Override
public void commit(Object obj) {
String str = (String)obj;
// Write the String to a file.
write(str);
}
@Override
public void rollback() {
// Obtain a handler to the File we are writing to, and delete the file.
// This returns the file system to the state it was in before we created a file and started writing to it.
File f = getFile();
// This is just pseudo-code for the sake of this example.
File.delete(f);
}
}
// Some method in a class somewhere...
public void doSomething(File someFile) {
TransactionalFileWriter txFileWriter = getTxFW(someFile);
try {
txFileWriter.commit("Create the file and write this message to it.");
} catch(Throwable t) {
txFileWriter.rollback();
}
}
不要太沉迷于上面的实际代码。这个想法很简单:一个事务文件编写器,它创建一个文件并写入它。它的rollback()
方法删除文件,从而将文件系统返回到commit(Object)
.
我在这里错过了什么吗?这就是 JTA 提供的全部内容吗?还是我上面的简单示例没有代表交易性的一组完全不同的维度/方面?我猜是后者,但尚未在 JTA 文档中看到任何具体内容。如果我遗漏了什么,那是什么,有人可以给我看具体的例子吗?我可以看到事务性是 JDBC 的一个重要组成部分,但希望获得一个 JTA 的示例,它与数据库以外的东西一起使用。