This is tangential to your question, but I'm adding it as an answer because your question is high on the Google results and there aren't a lot of examples of it out there.
With JDBI v2, you can use the @Transaction
annotation to simplify your code. Just decorate the public method with the annotation and JDBI will handle the begin, commit and rollback behind the scenes.
public abstract class JustinTest2 {
@SqlUpdate("INSERT INTO jTest2 (styleId, jNum) VALUES (:styleId, :jNum)")
protected abstract void insert(@Bind("styleId") int styleId, @Bind("jNum") int jNum);
@SqlQuery("SELECT count(styleId) " +
"FROM jTest2 " +
"WHERE styleId=:styleId")
protected abstract int findByStyleId(@Bind("styleId") int styleId);
@Transaction
public int doStuff(int styleId, int eventId) throws Exception{
int count = findByStyleId(styleId);
insert(styleId, eventId);
count = findByStyleId(styleId);
if(count==1) {
throw new Exception("Roll back");
}
return count;
}
}
Note that I made the insert
and findByStyleId
methods protected; down from public
to enforce they be done together in a transaction (in the public doStuff
method); not private
because the JDBI auto-generated implementation would not be able to override them (having methods be private abstract
doesn't work for that reason - you'd be forcing the compiler to accept a method without a body).
You can also specify a TransactionIsolationLevel
in the annotation to override your database's defaults.
@Transaction(TransactionIsolationLevel.REPEATABLE_READ)