トランザクション その1
実は SqlBatch アノテーションを付ければ勝手にトランザクション処理をしてくれます
Dao008.java
public interface Dao008 { @SqlBatch("insert into table001 (id, name) values (:id, :name)") int[] insertBatch(@Bind("id") List<Integer> ids, @Bind("name") List<String> names); @SqlQuery("select count(*) from table001") int findCount(); }
Sample014.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"); Dao008 dao008 = dbi.onDemand(Dao008.class); /* * 成功すれば勝手にcommitしてくれる */ List<Integer> ids = Arrays.asList(new Integer[]{1,2,3}); List<String> names = Arrays.asList(new String[]{"name1", "name2", "name3"}); System.out.println("before rows count = " + dao008.findCount()); // 0 try { int[] result = dao008.insertBatch(ids, names); System.out.println("result.length = " + result.length); // 3 } catch(Throwable e) { e.printStackTrace(); } System.out.println("after rows count = " + dao008.findCount()); // 3 /* * 失敗すれば勝手にrollbackしてくれる */ ids = Arrays.asList(new Integer[]{4,5,5}); names = Arrays.asList(new String[]{"name4", "name5", "name6"}); System.out.println("before rows count = " + dao008.findCount()); // 3 try { int[] result = dao008.insertBatch(ids, names); System.out.println("result.length = " + result.length); // 例外飛ぶのでここにはこない } catch(Throwable e) { e.printStackTrace(); } System.out.println("after rows count = " + dao008.findCount()); // 3 }