トランザクション その2

お次はバカ正直に自分でトランザクションを制御します

Sample015.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");
	Handle h = dbi.open();
	System.out.println("TransactionIsolationLevel = " + h.getTransactionIsolationLevel()); // ※1

	Integer count = 0;

	/*
	 * commit test
	 */
	count = h.createQuery("select count(*) from table001").map(IntegerMapper.FIRST).first();
	System.out.println("before rows count = " + count);

	try {
		h.begin();

		h.insert("insert into table001(id, name) values(?, ?)", 1, "name1");
		h.insert("insert into table001(id, name) values(?, ?)", 2, "name2");
		h.insert("insert into table001(id, name) values(?, ?)", 3, "name3");

		h.commit();
	} catch(Throwable e) {
		h.rollback();
		e.printStackTrace();
	}

	count = h.createQuery("select count(*) from table001").map(IntegerMapper.FIRST).first();
	System.out.println("after rows count = " + count);

	/*
	 * rollback test
	 */
	count = h.createQuery("select count(*) from table001").map(IntegerMapper.FIRST).first();
	System.out.println("before rows count = " + count);

	try {
		h.begin();

		h.insert("insert into table001(id, name) values(?, ?)", 4, "name4");
		h.insert("insert into table001(id, name) values(?, ?)", 5, "name5");
		h.insert("insert into table001(id, name) values(?, ?)", 5, "name6");

		h.commit();
	} catch(Throwable e) {
		h.rollback();
		e.printStackTrace();
	}

	count = h.createQuery("select count(*) from table001").map(IntegerMapper.FIRST).first();
	System.out.println("after rows count = " + count);
}

※1 でトランザクション分離レベルを出力しています。PostgreSQLだと READ_COMMITTED がデフォルトみたいです。もちろん setTransactionIsolation メソッドで他の分離レベルに変更可能です。