LoginSignup
1
0

More than 3 years have passed since last update.

[JAVA][Spring][MyBatis]SQLビルダーで GROUP BY を使う

Last updated at Posted at 2019-06-19

要求

  • Java の Springフレームワークを使ってDB操作したい。
  • mybatis のアノテーションとSQLビルダーを使う。
  • XMLを使いたくない。Javaで完結させたい。
  • GROUP BY を使いたい。

サンプル

以下のようなテーブル「shops」があるとする

shop_cd prefecture
0001 神奈川県
0002 神奈川県
0002 神奈川県
0003 神奈川県
0003 神奈川県
0004 東京都

「神奈川県」を指定しての店舗コードの重複しないリストがほしい。

public interface ShopMapper {
  /**
   * 都道府県を指定して店舗コードの一覧を取得する。
   *
   * @return List<Map<String, String>>
   *   結果ひとつあたりのMap
   *     - prefecture: 指定した都道府県名(日本語)
   *     - shopCd: 拠点コード
   */
  @SelectProvider(type = SqlProvider.class, method = "getShopCodesByPrefecture")
  @Results(id = "ShopCodesByPrefecture", value = {
          @Result(column = "shop_cd", property = "shopCd"),
          @Result(column = "prefecture", property = "prefecture"),
  })
  List<Map<String, String>> getShopCodesByPrefecture(String brandCd, String prefecture);

  class SqlProvider {
    public String getShopCodesByPrefecture(String prefecture) {
      SQL sql = new SQL() {
        {
          SELECT("shop_cd", "prefecture");
          FROM("shops");
          WHERE("shops.prefecture = #{prefecture}");
          GROUP_BY("shop_cd");
          ORDER_BY("shop_cd ASC");
        }
      };
      return sql.toString();
    }
  }
}

検索結果をMapでもらうように@Results@Resultの指定をした。

1
0
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
1
0