LoginSignup
4
5

More than 5 years have passed since last update.

Sql2oでアンダースコアが含まれたカラム名とPOJOのマッピング方法

Last updated at Posted at 2014-07-25

Sql2oで、update_at のようにアンダースコアが含まれたカラム名をPOJOの updateAt のようなプロパティ名にマッピングするには、2通りの方法がある。

方法1 #addColumnMapping(String, String)

Query#addColumnMapping(String, String) メソッドを使って、カラム名とPOJOのプロパティ名をマッピングする。

try (Connection con = sql2o.open()) {
  List<Foo> foos = con.createQuery(sql)
    // 第1引数はカラム名、第2引数はプロパティ名
    .addColumnMapping("update_at", "updateAt")
    .executeAndFetch(Foo.class);
}

カラム名の規約が統一されているのならば、Sql2oオブジェクトにあらかじめマッピングを登録しておける Sql2o#setDefaultColumnMappings(Map) メソッドで指定しておけば、より楽かもしれない。

// PostgreSQLの場合
sql2o =  new Sql2o(datasource, new PostgresQuirks());

// あらかじめ定義しておきたいマッピング
Map<String, String> colMaps = new HashMap<String,String>();
colMaps.put("update_at", "updateAt");

// マッピングの設定
sql2o.setDefaultColumnMappings(colMaps);

方法2 #setAutoDeriveColumnNames(boolean)

Query#setAutoDeriveColumnNames(boolean)メソッドを使うと、自動的にアンダースコアを考慮してマッピングしてくれる。

try (Connection con = sql2o.open()) {
  List<Foo> foos = con.createQuery(sql)
    .setAutoDeriveColumnNames(true)
    .executeAndFetch(Foo.class);
}

アンダースコアの考慮はUnderscoreToCamelCase.classのconvertメソッドで処理されている。

いちいちマッピング書かなくて楽なんだけど、Sql2oオブジェクトであらかじめ設定しておけるメソッドがないのは何でだろう?

参考文献

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5