Using @Transaction in JDBI / Dropwizard application
You can use @Transaction in JDBI. I have blogged about it here. http://manikandan-k.github.io/2015/05/10/Transactions_in_jdbi.html
The SQL Object API Overview shows the possibility to bind two instances to the same handle. This way you can both save()
calls as part of the same transaction:
// TODO: add try/catch/finally to close things properly
DBI dbi = new DBI("jdbc:h2:mem:test");
Handle h = dbi.open();
h.begin();
Dao1 dao1 = h.attach(Dao1.class);
Dao2 dao2 = h.attach(Dao2.class);
dao1.save(myBean1);
dao2.save(myBean2);
h.commit();
h.close();
If you use onDemand
instead of open
and hesitate to get try/catch right, you might want to consider something like this:
// add some more interfaces
public interface Dao1 extends GetHandle, Transactional<Dao1> {
@Query("insert into table1 ...")
save(myBean1);
}
DBI dbi = new DBI("jdbc:h2:mem:test");
Dao1 dao1 = dbi.onDemand(Dao1.class);
// no try/catch necessary here
dao1.inTransaction(transactional, status) -> {
transactional.save(myBean1);
transactional.withHandle((h) -> h.attach(Dao2.class)
.save(myBean2));
return null; // return is enforced by the interface
});
Please double-check the functionality with a unit test.