トランザクション その6

今回からObjectAPI形式とFluent形式を融合させてトランザクション処理をしてみましょう。まずは簡単なサンプルを。
2つ Handle を作って、1つは inTransaction メソッドでトランザクション処理を書きます。こいつは勝手にbegin〜commit〜rollbackをしてくれます。
そしてもう一つは別トランザクションからテーブルの行数を取得してます。
このサンプルは想定通りの挙動です。

Sample021.java
public static void main(String[] args) {
	String url = "jdbc:postgresql://192.168.52.128/jdbi";
	DBI dbi = new DBI(url, "jdbi_user", "jdbi_pass");
	final Handle otherHandler = dbi.open();
	final Handle h = dbi.open();

	h.insert("truncate table table001");

	System.out.println("before table001 rows count = " + countTable001(h)); // 0

	try {
		h.inTransaction(new TransactionCallback<Void>()
		{
			@Override
			public Void inTransaction(Handle handle, TransactionStatus status) throws Exception
			{
				System.out.println("[0] : count = " + countTable001(otherHandler)); // 0

				handle.insert("insert into table001(id,name) values(101, 'name101')");

				System.out.println("[1] : count = " + countTable001(otherHandler)); // 0

				handle.attach(Dao010.class).noTxSuccessTest();

				System.out.println("[2] : count = " + countTable001(otherHandler)); // 0

				return null;
			}
		});
	} catch(Throwable e) {
		e.printStackTrace();
	}

	System.out.println("after table001 rows count = " + countTable001(h)); // 4

	h.close();
	otherHandler.close();
}

public static int countTable001(final Handle h)
{
	return h.createQuery("select count(*) from table001").map(IntegerMapper.FIRST).first();
}

※Dao010.javaは以前出てきたやつを使いまわしてます