0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Spring BootでJPQLのIN句をLISTでの書き方

Posted at

検索機能などで実装することがあると思われるSQLのIN句

Ajaxを利用して、一覧テーブルの絞込検索機能を実装しました。その際にステータスによってチェックボックスで絞り込むような場面がありました。

// 送信するステータスIDの例
statusList = [2,3]

この値を利用して

SELECT * FROM 〇〇 WHERE △△ IN (2,3);

のようなSQLを作りたかったのですが、SQLとJPQLは書き方が違うんですよね。

ですがさすがJPQLといいますが、便利ですね。簡単でした

JPQLでのIN句の書き方


IN List型のプロパティ名

これだけで、IN句を作成できます。

大まかな流れのイメージ

1. HTMLのnameで配列名を指定

// Thymeleafを利用してhtmlは作成したので、th:valueでvalueをセット
<input name="statusList[]" type="checkbox" th:value="${status.id}">

2. javascriptでチェックされたやつのvalueを取得

var statusList = []; // ここにチェックされたvalueの値を格納
$('[name="status[]"]:checked').each(fuction(){
  // 一つずつ格納していく
  statusList.push(this.value);
});

3. Ajaxで送信


let data = [
statusList : statusList,
]

$.ajax({
  url : // 略
  method : 'POST',
  dataType : json',
  data: JSON.stringify(data), // ここにstatusListが入ってるんですね
  contentType : application/json',
})
.done( function (response) {
// 略

4. Controllerの引数で受け取る


@PostMapping
@ResponseBody
public String search(
@RequestBody List<Integer> statusList // これで受け取れる
){ // 略


// ラッパークラスを利用している場合
// 引数には
@RequestBody SearchForm searchForm

SearchForm.java(ラッパークラス)

public class SearchForm{

  private List<Integer> statusList; // Ajaxで送られてくるjsonのkey名に一致させる
  private String name;
  // その他フィールド

  // setter, getter略

}

ちゃんとこの中のフィールドに格納してくれます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?