-
Notifications
You must be signed in to change notification settings - Fork 0
Transactions
rnentjes edited this page Nov 19, 2012
·
11 revisions
With transactions we can make sure our operations are atomic, it also helps performance since we will only need one (disc) sync operation per transaction.
Transactions are maintained within a ThreadLocal, every store and remove operation is stored in the current transaction and applied to the model at commit time.
Please note:
- Running queries will take the current transaction into account, so if you removed an object it will not show up in a query even if you have not committed yet.
- Not calling commit or rollback on a transaction will throw an exception the next time a transaction is started on the same thread. Atm this will not recover on it's own.
- In autocommit mode every store and remove get's it's own transaction. Storing/removing multiple object in one call (dao.store(M ... objects)) will have the effect that they share that transaction.
- When there are no changes in the transaction at commit time the transaction is discarded and no sync operation is performed.
import nl.astraeus.prevayler.Transaction;
public class Test {
public static void main(String [] args) {
new Transaction() {
@Override
public void execute() {
Company company = new Company("Company x");
Employee employee1 = new Employee(company, "Employee x1");
Employee employee2 = new Employee(company, "Employee x2");
Employee employee3 = new Employee(company, "Employee x3");
companyDao.store(company, employee1, employee2, employee3);
Company c = companyDao.find(company.getId());
System.out.println("Found company: "+c); // finds company "x"
}
};
}
public void orDoItYourself() {
try {
SimpleStore.begin();
Company company = new Company("Company x");
companyDao.store(company);
Company c = companyDao.find(company.getId());
System.out.println("Found company: "+c); // finds company "x"
SimpleStore.rollback();
Company c = companyDao.find(company.getId());
System.out.println("Found company: "+c); // null
} finally {
if (SimpleStore.hasTransaction()) {
SimpleStore.rollback();
}
}
}
}Next Concurrency