トランザクション その3

次はDaoに@Transactionアノテーションを付けてトランザクション制御してみます

Dao010.java
public abstract class Dao010 {
	@SqlUpdate("insert into table001 (id, name) values (:id, :name)")
	public abstract int insert(@Bind("id") int id, @Bind("name") String name);

	@SqlQuery("select count(*) from table001")
	public abstract int findCount();

	@Transaction
	public void txSuccessTest()
	{
		insert(1, "name1");
		insert(2, "name2");
		insert(3, "name3");
	}

	@Transaction
	public void txErrorTest()
	{
		insert(4, "name4");
		insert(5, "name5");
		insert(5, "name6"); // ここでエラー
	}

	public void noTxSuccessTest()
	{
		insert(11, "name11");
		insert(12, "name12");
		insert(13, "name13");
	}

	public void noTxErrorTest()
	{
		insert(14, "name14");
		insert(15, "name15");
		insert(15, "name16"); // ここでエラー
	}
}
Sample016.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");
	Dao010 dao = dbi.onDemand(Dao010.class);

	// =====================================================================
	// @Transaction アノテーション有り
	// =====================================================================

	/*
	 * 成功すれば勝手にcommitしてくれる
	 */
	System.out.println("tx success before rows count = " + dao.findCount()); // 0
	try {
		dao.txSuccessTest();
	} catch(Throwable e) {
		e.printStackTrace();
	}
	System.out.println("tx success after rows count = " + dao.findCount()); // 3

	/*
	 * 失敗すれば勝手にrollbackしてくれる
	 */
	System.out.println("tx error before rows count = " + dao.findCount()); // 3
	try {
		dao.txErrorTest();
	} catch(Throwable e) {
		e.printStackTrace();
	}
	System.out.println("tx error rows count = " + dao.findCount()); // 3

	// =====================================================================
	// @Transaction アノテーション無し
	// =====================================================================

	/*
	 * 成功すれば当然auto-commit
	 */
	System.out.println("non-tx success before rows count = " + dao.findCount()); // 3
	try {
		dao.noTxSuccessTest();
	} catch(Throwable e) {
		e.printStackTrace();
	}
	System.out.println("non-tx success after rows count = " + dao.findCount()); // 6

	/*
	 * 失敗しても途中までcommitしてしまう
	 */
	System.out.println("non-tx error before rows count = " + dao.findCount()); // 6
	try {
		dao.noTxErrorTest();
	} catch(Throwable e) {
		e.printStackTrace();
	}
	System.out.println("non-tx error after rows count = " + dao.findCount()); // 8
}