LoginSignup
1
1

More than 3 years have passed since last update.

[JAVA][Spring][MyBatis]SQLビルダーで IN() を使う

Last updated at Posted at 2019-06-20

要求

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

サンプル

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

shop_cd name
0001 本店
0002 辞書店
0003 文庫店
0004 絵本店

WHERE shop_cd IN (0001, 0002)を指定して店舗一覧がほしい。

データを保持するクラス

@Getter
@Setter
public class Shop {
  private String shopCd;
  private String name;
}

マッパー

public interface ShopMapper {
  /**
   * 店舗コードのリストを受け取って店舗のリストを返す
   */
  @SelectProvider(type = SqlProvider.class, method = "selectByShopCodes")
  List<Shop> selectByShopCodes(List<String> shopCodes);

  class SqlProvider {
    public String selectByShopCodes(List<String> shopCodes) {
      final String inParams = getInPhraseParamString(shopCodes, "shopCodes");
      SQL sql = new SQL() {
        {
          SELECT("*");
          FROM("shops");
          WHERE(String.format("shops.shop_cd IN (%s)", inParams));
          ORDER_BY("shop_cd ASC");
        }
      };
      return sql.toString();
    }

    /**
     * リストを受け取って IN () 句で利用するパラメータ文字列を返す
     * 例: #{shopCodes[0]}, #{shopCodes[1]}, #{shopCodes[2]}
     */
    private String getInPhraseParamString(List<String> values, String paramName) {
      String paramString = "";
      int i = 0;
      for (String value : values) {
        if (i != 0) {
          paramString += ",";
        }
        paramString += String.format("#{%s[%s]}", paramName ,i);
        i++;
      }
      return paramString;
    }
  }
}

コツ

  • #{リスト[0]}, #{リスト[1]}, #{リスト[2]} ... という文字列をリストの長さに合わせて作成しIN句で利用する。
  • 引数名(サンプルでは「shopCodes」)とSQL内での指定変数名(サンプルでは「#{shopCodes[0]}」)とを一致させること。
1
1
1

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
1