insertした時のidを取得する その1
よくあるRESTのパターンとして、IDはシーケンスを設定しておき、APIから指定された内容を登録したらIDを返す、というもの。JDBIではどうやればいいのかというサンプルです。
Dao017.java
public interface Dao017 { @SqlUpdate("CREATE SEQUENCE seq") void createSequence(); @SqlUpdate("CREATE TABLE IF NOT EXISTS table003 (id int DEFAULT nextval('seq'), name text, CONSTRAINT id_pkey PRIMARY KEY ( id ))") void createTable(); @SqlUpdate("insert into table003 (name) values (:name)") @GetGeneratedKeys int insert(@Bind("name") String name); @SqlQuery("select name from table003 where id = :id") String findNameById(@Bind("id") int id); }
Sample026.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"); Dao017 dao = dbi.onDemand(Dao017.class); try { dao.createSequence(); // 2回目以降既に存在するエラーが起きるけど無視する dao.createTable(); } catch(Throwable e) { } int id1 = dao.insert("name1"); int id2 = dao.insert("name2"); System.out.println("id1 = " + id1); System.out.println("id2 = " + id2); System.out.println("name of id1 = " + dao.findNameById(id1)); System.out.println("name of id2 = " + dao.findNameById(id2)); }
ソースを見てもらえればわかる通り、GetGeneratedKeys アノテーションを付けるとinsert後、insertした時に割り振られたシーケンス値が返ってきます